0

How can I create an array containing the values of people that have the same office

const arr = [
  { "officeID": "1", "people": 10},
  { "officeID": "2", "people": 10 },
  { "officeID": "1", "people": 20 }
]

The intented outcome should be an array[10,20] containing the values of people that have the same office id

0

1 Answer 1

2

I suppose you count the total people in each office as you want to merge.

const arr = [
  { officeID: '1', people: 10 },
  { officeID: '2', people: 40 },
  { officeID: '1', people: 20 },
];

let ret = arr.reduce((prev, c) => {
  const p = prev;
  if (!p[c.officeID]) p[c.officeID] = [c.people];
  else p[c.officeID] = [...p[c.officeID], c.people];
  return p;
}, {});

ret = Object.entries(ret).map((x) => ({ officeID: x[0], people: x[1] }));
console.log(ret);

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

4 Comments

const arr = [ { officeID: "1", people: 10 }, { officeID: "2", people: 40 }, { officeID: "1", people: 20 }, ]; The intended outcome would be an array [10,20] . These are the values of people that have the same office.
Do you want group the same office people as an array like [{ officeID: "1", people: [10, 20] }, { officeID: "2", people: [40] }].
yes exactly @mr hr
@StLoiz now check it. I have updated the code according to your requirement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.