0

How can I make this code return values instead of arrays? This is my representation, where the idea is to check whether IDs match between each other and get a priceList array of matching values. Can this be simplified, or perhaps replaced with .reduce()? Need extra help with this

const priceList = options.map((productOption) => {
  const { data } = productOption;

  return data.filter(({ option_type_id, price }) => {
    if (selectedOptionsArray.indexOf(option_type_id) !== -1) {
      return price;
    }

    return 0;
  });
});
4
  • I couldn't understand, what you want to do, but Array.prototype.map always returns an array. Commented Apr 14, 2021 at 10:28
  • @ASDFGerte maybe OP means that they get nested arrays? in which case, .map -> .flatMap. But if it's something different, I'm not sure. Commented Apr 14, 2021 at 10:30
  • The callback of .filter() has to return a boolean. Why do you return an arbitrary number instead? Commented Apr 14, 2021 at 10:33
  • use map instead of filter you will get an array of numbers. Commented Apr 14, 2021 at 10:35

1 Answer 1

1

I hope this helps: I have assumed few data (options and selectedOptionsArray)

Also there can be duplicate price in the priceList as multiple product can have same price. You can fix that by using Set: let uniqueItems = [...new Set(itemsArray)]

const options = [{
    data: [{
        option_type_id: 1,
        price: 100
    }, {
        option_type_id: 2,
        price: 200
    }]
}, {
    data: [{
        option_type_id: 3,
        price: 300
    }, {
        option_type_id: 4,
        price: 400
    }]
}]

const selectedOptionsArray = [1,3,4];

const priceList = options.flatMap((productOption) => productOption.data).reduce((accumulator, currentValue) => {
    const { option_type_id, price } = currentValue;
    if (selectedOptionsArray.indexOf(option_type_id) !== -1) {
      return [...accumulator, price];
    }
    return accumulator;
  }, []);
  
 console.log(priceList);

Sign up to request clarification or add additional context in comments.

Comments

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.