동일한 항목을 가진 숫자 배열이 있습니다. 배열을 가져와서 동일한 모든 항목을 하나의 하위 배열로 그룹화하고 이렇게 형성된 새 배열을 반환하는 함수를 작성해야 합니다.
예:입력 배열이 -
인 경우const arr = [234, 65, 65, 2, 2, 234];
// 출력은 −
여야 합니다.const output = [[234, 234], [65, 65], [2, 2]];
Hashmap을 사용하여 이미 발생한 요소를 추적하고 for 루프를 사용하여 배열을 반복합니다.
따라서 이 함수의 코드를 작성해 보겠습니다 -
예시
이에 대한 코드는 -
const arr = [234, 65, 65, 2, 2, 234];
const groupArray = arr => {
const map = {};
const group = [];
for(let i = 0; i < arr.length; i++){
if(typeof map[arr[i]] === 'number'){
group[map[arr[i]]].push(arr[i]);
}else{
//the push method returns the new length of array
//and the index of newly pushed element is length-1
map[arr[i]] = group.push([arr[i]])-1;
}
};
return group;
}
console.log(groupArray(arr)); 출력
콘솔의 출력은 -
[ [ 234, 234 ], [ 65, 65 ], [ 2, 2 ] ]