Home > front end >  How to loop through indexes and find matching values Javascript
How to loop through indexes and find matching values Javascript

Time:10-30

So I have this function where I'm looking to find any index where the text is equal to the other objects text.

How could I do this using a for loop to figure out if any index (i.e: 1-10 or 10-1) matches the other in any random order?


const foundExistingProductWithExtra = state.products.findIndex(
        (product) =>
          product._id === action.payload._id &&
          product.extras[0]?.text === currentProductExtras[0]?.text &&
          product.extras[1]?.text === currentProductExtras[1]?.text &&
          product.extras[2]?.text === currentProductExtras[2]?.text &&
          product.extras[3]?.text === currentProductExtras[3]?.text
      );

This is obviously not the ideal way to do it but that's what I'm working with.

CodePudding user response:

const currentProductExtraTexts = JSON.stringify(currentProductExtras.map(i=>i.text).sort();
const foundExistingProductWithExtra = state.products.findIndex(product =>
  product._id === action.payload._id &&
  JSON.stringify(product.extras.map(i=>i.text).sort()) === currentProductExtraTexts)
);
  • Related