Mart Fijten
Mart Fijten

Reputation: 59

How to push object value with the same property value to the same subarray in Javascript?

I'm unsure how to word the title of this question so I hope my explanation will make more sense. I have an array with 190 objects, each containing six keys and values, like this:

enter image description here

My goal is to create an array that starts with a year, followed by all Values from that year, like this:

[
  [2000,16707,2416,8653,22176,1047,24096,27045,86019,27667,231],
  [2001,18249,2605,8458,22164,1181,24785,26497,85163,28912,316],
  [2002,.....]
  ...
]

Right now, this is my code:

var dataNumbers = new Array();

for (var i = 0; i < data.length; i++) {
  if (data[i].Countries == country) {
    dataNumbers.push([data[i].Periods, data[i].Value])
  }
}

This results in an array that looks like this:

[
  [2000,16707],
  [2000,2416],
  [2000,8653],
  [2000,22176],
  ...
  ...
]

How can I group all numbers that match in my case Periods as shown above?

Upvotes: 1

Views: 185

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take an object as hash table for grouping the same Peroids and get the values of the hash table as result.

result = Object.values(data.reduce((r, { Periods, Value }) => {
    r[Periods] = r[Periods] || [Periods];
    r[Periods].push(Value);
    return r;
}, {}));

A slightly different approach with a Map.

result = Array.from(
    data.reduce((m, { Periods, Value }) => m.set(Periods, [...(m.get(Periods) || []), Value]), new Map),
    (k, v) => [k, ...v]
);

Upvotes: 1

Related Questions