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

การเลื่อนอิลิเมนต์เฉพาะไปท้ายอาร์เรย์ใน JavaScript


ภาพรวม

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ตัวเลขเป็นอาร์กิวเมนต์แรก และตัวเลขเดี่ยวเป็นอาร์กิวเมนต์ที่สอง ฟังก์ชันควรตรวจสอบทุกครั้งที่ตัวเลขที่สองปรากฏในอาร์เรย์ และเลื่อนไปท้ายอาร์เรย์

ตัวอย่าง

อินพุต: const arr = [1, 5, 6, 6, 5, 3, 3];, ตัวเลข: 6

เอาต์พุต: const output = [1, 5, 5, 3, 3, 6, 6];

ตัวอย่างโค้ด

const arr = [1, 5, 6, 6, 5, 3, 3];
const num = 6;

const shiftElement = (arr, num) => {
  if (arr.length === 0) {
    return arr;
  }
  let index = 0;
  for(let e of arr) {
    if(e !== num) {
      arr[index] = e;
      index += 1;
    }
  }
  for (; index < arr.length; index++) {
    arr[index] = num;
  }
};

shiftElement(arr, num);
console.log(arr);

ผลลัพธ์ในคอนโซล

[ 1, 5, 5, 3, 3, 6, 6 ]