skip to Main Content
let arr = [1, 2, 3, 4, 5];

for (let i = 0; i <= arr.length - 1; i++) {
  let ar = arr.splice(i, 1);
  console.log(ar.flat())
}

I have an array. 1 kills 2, 3 kills 4 like and array is [1,3,5]. 5 kills 1, 3 kills 5, and so on. Final operation is 3. How to do in JavaScript?

2

Answers


  1. The below code seems to work, we just need to reset the index when its crosses the array limit and a while loop will run until we only have one element in the array, then the logic seems to work!

    let arr = [1, 2, 3, 4, 5];
    
    /*
    for(let i=0;i<=arr.length-1;i++){
    let ar = arr.splice(i,1);
    console.log(ar.flat())
    }
    */
    let index = 0;
    while (arr.length > 1) {
      index = index < arr.length - 1 ? index + 1 : 0;
      arr.splice(index, 1);
    }
    
    console.log(arr);
    .as-console-wrapper {
      top: 0;
      max-height: 100% !important;
    }
    Login or Signup to reply.
  2. let arr = [1, 2, 3, 4, 5];
    while (arr.length > 1)
      arr = arr.filter(() => this.del ? --this.del : this.del = +1, { del: 1 })
    console.log(arr)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search