Javascript: Convert Array into Object

Viewed 98

i have array:

[
  ['a', 'b', 'c'],
  ['a', 'h', 'k'],
  ['c', 'd', 'e']
]

Is there a best way to convert it on object like this?

{
  a: [
       ['a', 'b', 'c'],
       ['a', 'h', 'k'],
     ],
  c: [
       ['c', 'd', 'e']
     ]
}
2 Answers

You can achieve it by using .reduce & Logical nullish assignment (??=)

const arrays = [
  ['a', 'b', 'c'],
  ['a', 'h', 'k'],
  ['c', 'd', 'e']
];

const result = arrays.reduce((acc, curr) => {
  const key = curr[0];
  acc[key] ??= [];
  acc[key].push(curr);
  
  return acc;
}, {})

console.log(result);

You can use .reduce() to get the desired output:

const data = [
  ['a', 'b', 'c'],
  ['a', 'h', 'k'],
  ['c', 'd', 'e']
];

const result = data.reduce((r, c) => {
  r[c[0]] = r[c[0]] || [];
  r[c[0]].push(c);
  return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related