Search code examples
javascriptarraystypescriptjavascript-objects

First Item kills next item up to array length is equal 1 in JavaScript


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?


Solution

  • I used Array.filter and switcher(to filter an element or not): this.del that works alternately(1/0) after each element of the Array. 0 is false(to filter), 1 is true(not to filter). The context of switcher (this) is relative to the while loop and remains after every turn.

    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)