Reduce elements in nested array

Viewed 65

I am trying to filter an array and reduce values, but I don't know how.

So, I have a example array [["Hampton Tricep Rope", 3],["Chrome Curl" Bar,8],["Hampton Tricep Rope", 6]]

How to create a function with return [["Hampton Tricep Rope", 9],["Chrome Curl" Bar,8]] ?

Do you have any idea?

3 Answers

You can use Array.prototype.reduce() to return an object which contains each unique name and its value.

Finally use Object.entries() to get an array with the key and value from that object.

const arr = [["Hampton Tricep Rope", 3],["Chrome Curl Bar", 8],["Hampton Tricep Rope", 6]];

const res = Object.entries(arr.reduce((acc, [name, value]) => {
 if(!acc[name]) {
   acc[name] = value;
 } else {
   acc[name] += value; 
 }
 
 return acc;
}, {}))

console.log(res);

Object.entries

You could use reduce and findIndex

const list = [
  ["Hampton Tricep Rope", 3],
  ["Chrome Curl Bar", 8],
  ["Hampton Tricep Rope", 6]
].reduce((acc, x) => {
  const index = acc.findIndex(y => y[0] === x[0]);
  if (index >= 0) {
    acc[index][1] += x[1];
    return acc;
  }
  acc.push(x);
  return acc;
}, [])

console.log(list)

var result = [];
[["Hampton Tricep Rope", 3],["Chrome Curl Bar",8],["Hampton Tricep Rope", 6]].reduce(function(res, value) {
  if (!result.filter((item) => (item[0] === value[0])).length) {
    result.push([value[0], value[1]]);
  } else {
    result.filter((item) => (item[0] === value[0]))[0][1] += value[1];
  }
  return res;
}, {});

We need an array to construct while we reduce the other, as you can see above. At each step we check whether we already have the element. If not, then we add it. Otherwise we increase it according to our needs.

Related