สมมติว่า เรามีอาร์เรย์ของตัวเลขที่มีรายการที่เหมือนกัน เราจำเป็นต้องเขียนฟังก์ชันที่รับอาร์เรย์และจัดกลุ่มรายการที่เหมือนกันทั้งหมดไว้ในอาร์เรย์ย่อยเดียวและส่งกลับอาร์เรย์ใหม่ที่เกิดขึ้น
ตัวอย่างเช่น หากอาร์เรย์อินพุตเป็น −
const arr = [234, 65, 65, 2, 2, 234];
จากนั้นผลลัพธ์ควรเป็น −
const output = [[234, 234], [65, 65], [2, 2]];
เราจะใช้ hashmap เพื่อติดตามองค์ประกอบที่เกิดขึ้นแล้วและวนซ้ำในอาร์เรย์โดยใช้ for loop
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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 ] ]