0

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 Answer 1

3

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);

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

1 Comment

Works like a treat thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.