2

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.

1 Answer 1

1
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)
);
Sign up to request clarification or add additional context in comments.

3 Comments

I appreciate the quick response. Unfortunately, it doesn't work quite how I was intending because it returns true when it finds the first matching extra item. If I were to add another index with a new extra object, then the extra shouldn't match unless it has that extra item and so on. It would look like this: [0] {text: "first extra"} [1] {text: "second extra"} [2] {text: "third extra"} and so on. If an item has all 3, then it matches but if it only matches one or two, then it isn't the same product.
@thatnewguy8 I updated the answer. Is that what you mean?
@thatnewguy8 great, I've also taken one of the stringify operations out of the loop, since it will be the same value for each loop iteration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.