Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ลบค่าซ้ำในอาร์เรย์แต่คงความยาวเดิมไว้ใน JavaScript

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ ลบค่าซ้ำทั้งหมด และแทรกสตริงว่างจำนวนเท่ากันที่ท้ายอาร์เรย์

ตัวเช่น - ถ้าเราพบค่าซ้ำ 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, '', '', '', '', '', '', '', '', '', '' ]