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"
]
0

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Brk, thanks for your answer man! This solution fits perfect for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.