다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
]; uuid 속성 값이 유사한 별도의 배열 배열로 개체를 분할하는 JavaScript 함수를 작성해야 합니다.
출력
따라서 출력은 다음과 같아야 합니다. -
const output = [
[
{"name": "toto", "uuid": 1111},
{"name": "titi", "uuid": 1111}
],
[
{"name": "tata", "uuid": 2222}
]
]; 이에 대한 코드는 -
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)); 출력
콘솔의 출력 -
[
[ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
[ { name: 'tata', uuid: 2222 } ]
]