Search code examples
javascriptarraysfindlookupreduce

how to return new array by using array.reduce


I want to return new array by using reduce. For example,

const product = [
  { color: 'orange', type: 'hat', count: 1 },
  { color: 'orange', type: 'hat', count: 1 },
  { color: 'orange', type: 'shoes', count: 1 },
  { color: 'blue', type: 'food', count: 1 },
];

the product list need to like below because there are two 'hat' therefore, the count should be 2 and one { color: 'orange', type: 'hat', count: 1 } should be removed.

const result = product.reduce((acc, curr) => {
// I want to make new array like
// const product = [
//  { color: 'orange', type: 'hat', count: 2 },
//  { color: 'orange', type: 'shoes', count: 1 },
//  { color: 'blue', type: 'food', count: 1 },
//];
 return acc
}

thank you!


Solution

  • I would do it the following way :

    • First find if the product has already been added to the curr array
    • If yes, increments the count
    • else, push the new product into the array

    Note : I've used the Spread operator to make a deep copy of the object instead of pushing the current object into the array.

    This result by not modifying the products array and create a completely new array

    const product = [
      { color: 'orange', type: 'hat', count: 1 },
      { color: 'orange', type: 'hat', count: 1 },
      { color: 'orange', type: 'shoes', count: 1 },
      { color: 'blue', type: 'food', count: 1 },
    ];
    
    const result = product.reduce((acc, curr) => {
     if(!acc) return [...curr]
     
     const exist = acc.find(x => x.type === curr.type && x.color === curr.color)
     exist ? exist.count += 1 : acc.push({...curr})
     return acc
    }, [])
    
    console.log(result)