How to combine duplicate object value in the array then output a list?

Viewed 71

I've been working on this couple hours and google around, see lots of example for remove duplicate, but not combined the value. so I hope someone can help me out here.

I want to check the item.name is the same, then add the price together then push to new list array.

const items = [
  { name: 'apple',      price: '10' },
  { name: 'banana',     price: '1' },
  { name: 'orange',     price: '2' },
  { name: 'apple',      price: '5' },
  { name: 'orange',     price: '2.5' },
  { name: 'banana',     price: '3' },
  { name: 'strawberry', price: '7' },
  { name: 'apple',      price: '12' }
]

let newItem = []
const checkItem = items.map((prev, next) => {
  if (prev.name === next.name) {
    return newItem.push = {
      name: next.name,
      value: parseInt(prev.price) + parseInt(next.price)
    }
  }
});

console.log(newItem)

Big thanks for the help!

2 Answers

This will work.You can use reduce with Find.

const items = [{
    name: 'apple',
    price: '10'
  },
  {
    name: 'banana',
    price: '1'
  },
  {
    name: 'orange',
    price: '2'
  },
  {
    name: 'apple',
    price: '5'
  },
  {
    name: 'orange',
    price: '2.5'
  },
  {
    name: 'banana',
    price: '3'
  },
  {
    name: 'strawberry',
    price: '7'
  },
  {
    name: 'apple',
    price: '12'
  }
]

let result = items.reduce((acc, el) => {
  if (acc.filter(ele => ele.name == el.name).length == 0) {
    acc.push(el);
  } else {
    let filtered = acc.find(ele => ele.name == el.name)
    filtered.price = parseFloat(filtered.price) + parseFloat(el.price);
}
return acc;

}, [])

console.log(result)

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

The Array​.prototype​.map()'s callback functions first two arguments are currentValue i.e item of the array and second value is it's index, & not prev and next elements.

What you are looking for is something like this.

const items = [
  { name: "apple", price: "10" },
  { name: "banana", price: "1" },
  { name: "orange", price: "2" },
  { name: "apple", price: "5" },
  { name: "orange", price: "2.5" },
  { name: "banana", price: "3" },
  { name: "strawberry", price: "7" },
  { name: "apple", price: "12" }
];

const combine = items.reduce((acc, item) => {
  if (acc[item.name] !== undefined) {
    acc[item.name] += Number(item.price);
  } else acc[item.name] = Number(item.price);
  return acc;
}, {});

const fruitKeys = Object.keys(combine);

newItem = fruitKeys.map(item => ({ name: item, price: combine[item] }));

console.log(newItem);

I have split the solution into two steps, namely combine and reconstruction of the object so that you can clearly see what's happening.

I highly recommend you to refer the documentation for reduce method to understand its working

Related