เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ เข้ามา ลบค่าซ้ำทั้งหมด และแทรกสตริงว่างจำนวนเท่ากับจำนวนค่าที่ลบไปไว้ที่ท้ายอาร์เรย์
เช่น ถ้าพบค่าซ้ำ 4 ค่า ให้ลบทั้งหมดและแทรกสตริงว่าง 4 ตัวที่ท้าย
ตัวอย่าง
โค้ดต่อไปนี้เป็นตัวอย่าง:
const arr = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];
const deleteAndInsert = arr => {
const creds = arr.reduce((acc, val, ind, array) => {
let { count, res } = acc;
if(array.lastIndexOf(val) === ind){
res.push(val);
}else{
count++;
};
return {res, count};
}, {
count: 0,
res: []
});
const { res, count } = creds;
return res.concat(" ".repeat(count).split(" "));
};
console.log(deleteAndInsert(arr));ผลลัพธ์
จะแสดงผลในคอนโซลดังนี้:
[ 2, 3, 5, 12, 23, 4, 1, '', '', '', '', '', '', '', '', '', '', '' ]