D
D
dmitry20002021-06-28 13:15:10
JavaScript
dmitry2000, 2021-06-28 13:15:10

How to make the n-th number of arrays from an array of objects by value in the object?

There is an array of objects, for example:

let h = [
                {
                    name: 'Petya',
                    id: 1
                },
                {
                    name: 'Vasya',
                    id: 2
                },
                {
                    name: 'Kolya',
                    id: 3
                },
                {
                    name: 'Sveta',
                    id: 1
                }
            ];

            let h1 = [
                {
                    name: 'Petya',
                    id: 1
                },
                {
                    name: 'Sveta',
                    id: 1
                }
            ];

            let h2 = [
                {
                    name: 'Vasya',
                    id: 2
                }
            ];

            let h3 = [
                {
                    name: 'Kolya',
                    id: 3
                }
            ];


The h array contains everything. I would like to divide into the n-th number of arrays, for example, by id, where unique ids will be collected in each array, and all the elements that are there. Those. as a result, I want to get arrays h1, h2, h3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-28
@dmitry2000

as a result, I want to get arrays h1, h2, h3

In general, you don't know how many different id's there will be and what their values ​​will be. So you don't just need arrays, they should be folded into an object (or Map):
const grouped = arr.reduce((acc, n) => ((acc[n.id] ??= []).push(n), acc), {});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question