เรามีอาร์เรย์ของตัวเลขที่มีรายการซ้ำซ้อน งานของเราคือการเขียนฟังก์ชันที่รับอาร์เรย์และจัดกลุ่มรายการที่เหมือนกันทั้งหมดไว้ในอาร์เรย์ย่อยเดียวและส่งกลับอาร์เรย์ใหม่ที่เกิดขึ้น
ตัวอย่างเช่น −
//If the input array is: const arr = [1, 3, 3, 1]; //then the output should be: const output = [[1, 1], [3, 3]];
เราจะใช้ HashMap เพื่อติดตามองค์ประกอบที่เกิดขึ้นแล้วและวนซ้ำผ่าน thearray โดยใช้ for loop รหัสสำหรับสิ่งนี้จะเป็น -
ตัวอย่าง
const arr = [1, 3, 3, 1];
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)); ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
[ [ 1, 1 ], [ 3, 3 ] ]