Group by element in array JavaScript
https://www.tutorialspoint.com/group-by-element-in-array-javascript
質問
Group by element in array JavaScript
Suppose, we have an array of objects like this −
const arr = [ {"name": "toto", "uuid": 1111}, {"name": "tata", "uuid": 2222}, {"name": "titi", "uuid": 1111} ];
We are required to write a JavaScript function that splits the objects into separate array of arrays that have the similar values for the uuid property.
Output
Therefore, the output should look like this −
const output = [ [ {"name": "toto", "uuid": 1111}, {"name": "titi", "uuid": 1111} ], [ {"name": "tata", "uuid": 2222} ] ];
The code for this will be −
const arr = [ {"name": "toto", "uuid": 1111}, {"name": "tata", "uuid": 2222}, {"name": "titi", "uuid": 1111} ]; const groupByElement = arr => { const hash = Object.create(null), result = []; arr.forEach(el => { if (!hash[el.uuid]) { hash[el.uuid] = []; result.push(hash[el.uuid]); }; hash[el.uuid].push(el); }); return result; }; console.log(groupByElement(arr));
Output
The output in the console −
[ [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ], [ { name: 'tata', uuid: 2222 } ] ]
Advertisements
所属していません Tutorialspoint