เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ตัวเลขที่มีรายการซ้ำ และรวมค่าซ้ำทั้งหมดเป็นดัชนีเดียว
ตัวอย่าง
โค้ดสำหรับนี้:
const input = [1, 3, 1, 3, 5, 7, 5, 3, 4]; const sumDuplicate = arr => { const map = arr.reduce((acc, val) => { if(acc.has(val)){ acc.set(val, acc.get(val) + 1); }else{ acc.set(val, 1); }; return acc; }, new Map()); return Array.from(map, el => el[0] * el[1]); }; console.log(sumDuplicate(input));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
[ 2, 9, 10, 7, 4 ]