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 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);
answered Feb 3, 2021 at 9:10
Nguyễn Văn Phong
14.2k19 gold badges48 silver badges65 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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; }
answered Feb 3, 2021 at 8:42
Mohammad Usman
39.5k20 gold badges99 silver badges101 bronze badges
2 Comments
Nguyễn Văn Phong
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? sirNguyễn Văn Phong
Also, you can make your code more concise like from
r[c[0]] = r[c[0]] || []; to acc[key] ??= [];. Check my answer below if you like. Thanks sir :)lang-js
'0'as the property you want to group by.