เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลข
อาร์เรย์อาจมีรายการซ้ำ/ซ้ำกันภายใน ฟังก์ชันของเราควรบวกค่าซ้ำทั้งหมดและคืนค่าอาร์เรย์ใหม่ที่สร้างขึ้น
ตัวอย่างโค้ด
โค้ดสำหรับการทำงานนี้จะเป็นดังนี้
const arr = [20, 20, 20, 10, 10, 5, 1];
const sumIdentical = (arr = []) => {
let map = {};
for (let i = 0; i < arr.length; i++) {
let el = arr[i];
map[el] = map[el] ? map[el] + 1 : 1;
};
const res = [];
for (let count in map) {
res.push(map[count] * count);
};
return res;
};
console.log(sumIdentical(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[ 1, 5, 20, 60 ]