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']
 ]
}
asked Feb 3, 2021 at 8:36
4

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

answered Feb 3, 2021 at 8:42

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.