[Vuejs]-Reduce and sum array of objects (JS)

3๐Ÿ‘

โœ…

You can use Array.reduce():

var models = [
    { id: 1, name: "samsung", seller_id: 1, count: 56 },
    { id: 1, name: "samsung", seller_id: 2, count: 68 },
    { id: 2, name: "nokia", seller_id: 2, count: 45 },
    { id: 2, name: "nokia", seller_id: 3, count: 49 }
];

var arr = models.reduce((acc, item) => {
  let existItem = acc.find(({id}) => item.id === id);
  if(existItem) {
    existItem.count += item.count;
  } else {
    acc.push(item);
  }
  return acc;
}, []);

console.log(arr);

So, for your code, you can use this.arr and this.models replacing those variables from above which will look something like:

this.arr = this.models.reduce((acc, item) => {
  let existItem = acc.find(({id}) => item.id === id);
  if(existItem) {
    existItem.count += item.count;
  } else {
    acc.push(item);
  }
  return acc;
}, []);

0๐Ÿ‘

You can use Object.values instead of some. Inside the reduce callback create an object with key as id and value from the models. Then use Object.values to create an array of the values

let models = [{
    id: 1,
    name: "samsung",
    seller_id: 1,
    count: 56
  },
  {
    id: 1,
    name: "samsung",
    seller_id: 2,
    count: 68
  },
  {
    id: 2,
    name: "nokia",
    seller_id: 2,
    count: 45
  },
  {
    id: 2,
    name: "nokia",
    seller_id: 3,
    count: 49
  }
]
let data = models.reduce((acc, curr) => {
  if (!acc[curr.id]) {
    acc[curr.id] = curr;
  } else {
    acc[curr.id].count += curr.count

  }
  return acc;
}, {})
console.log(Object.values(data))

Leave a comment