1

How can I group an array of objects after two properties? Is it possible to use reduce in the following case?

Ex: group the following array by country and city and sum the "age" property:

array = [
{
  age: 20,
  country: "England"
  city: "London",
  zip: "1234"
},
{
  age: 25,
  country: "England"
  city: "London",
  zip: "12345"
},
{
  age: 40,
  country: "England"
  city: "Manchester",
  zip: "123456"
}
]

/* expected result: */

expectedArray = [
{
  age: 45, /* 20 + 25 */
  country: "England"
  city: "London",
  zip: "Not relevant"
},
{
  age: 40,
  country: "England"
  city: "Manchester",
  zip: "NR"
]
Erik A
  • 31,639
  • 12
  • 42
  • 67
Decoder
  • 13
  • 2

1 Answers1

1

You can do that using findIndex. Using this array method find the index of the object from accumulator array where the city & country matches. This will give the index of the object other wise if there is no such object then it will return -1. If it is -1 then push the object from the main array in accumulator array of reduce

let array = [{
    age: 20,
    country: "England",
    city: "London",
    zip: "1234"
  },
  {
    age: 25,
    country: "England",
    city: "London",
    zip: "12345"
  },
  {
    age: 40,
    country: "England",
    city: "Manchester",
    zip: "123456"
  }
]

let newArray = array.reduce((acc, curr) => {
  let getIndex = acc.findIndex((item) => {
    return item.country === curr.country && item.city === curr.city
  });


  if (getIndex === -1) {
    acc.push(curr)
  } else {
    acc[getIndex].age += curr.age

  }

  return acc;
}, []);

console.log(newArray)
brk
  • 48,835
  • 10
  • 56
  • 78