2

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']
     ]
}
  • 1
    what is the rule to convert? ask the question clearly. – wangdev87 Feb 03 '21 at 08:37
  • https://stackoverflow.com/a/54789452/15064340 check this – Shivansh Seth Feb 03 '21 at 08:39
  • You can use any of the grouping questions like ([Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511) or [How to group an array of objects by key](https://stackoverflow.com/questions/40774697)). Use `'0'` as the property you want to group by. – adiga Feb 03 '21 at 08:40
  • it is to merge all the ways elements have an equal array [0] into one key of the object – Kiều Toàn Feb 03 '21 at 08:41

2 Answers2

2

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);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

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; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • You should cache the `c[0]` into an individual variable named `key` to make your code less complex as well as avoid duplication codes :) Is that ok if I edit it? sir – Nguyễn Văn Phong Feb 03 '21 at 09:34
  • 1
    Also, you can make your code more concise like from `r[c[0]] = r[c[0]] || [];` to `acc[key] ??= [];`. Check [my answer](https://stackoverflow.com/a/66024352/9071943) below if you like. Thanks sir :) – Nguyễn Văn Phong Feb 03 '21 at 09:36