Combining arrays on first Value in Javascript

Viewed 26

I have a loop that creates arrays like so but I want to find a way for grouping them from the fist values below I have show how the data is and the result I want how do I get the result from the data I have now.

['Brand', 'Workout', 12]
['Colour', 'Pink', 41]
['Fit', 'Regular', 238]
['Size', '10', 21]
['Type', 'T-Shirt', 139]
['Colour', 'Black', 71]
['Brand', 'Matalan', 13]


Brand: {
  Workout: 12,
  Matalan: 13
},
Colour: {
  Pink: 41,
  Black: 71
},
Fit: {
  Regular: 238
},
Size: {
  10: 21
},
Type: {
  T-Shirt: 139
}
1 Answers

You can use Array.prototype.reduce for that. What you want to do is, put your input arrays into an array, which creates a two-dimensional array.

After that is done, use Array.prototype.reduce to accumulate an object, and split the input: ['Brand', 'Workout', 12] into the parameters: [key, property, value].

const input = [
  ['Brand', 'Workout', 12],
  ['Colour', 'Pink', 41],
  ['Fit', 'Regular', 238],
  ['Size', '10', 21],
  ['Type', 'T-Shirt', 139],
  ['Colour', 'Black', 71],
  ['Brand', 'Matalan', 13]
];

const result = input.reduce((accumulator, [key, property, value]) => {
  accumulator[key] = {
    ...(accumulator[key] ?? {}),
    [property]: value
  };

  return accumulator;
}, {});

console.log(result);

Related