1

I want to write a function that removes every second element given that the array is longer than length 2. For instance:

removeEveryOther([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) returns [1, 3, 5, 7, 9]);
removeEveryOther([[1, 2]]) returns [[1, 2]])

Here is my try:

function removeEveryOther(arr){

  for (i=0; i < arr.length; i++) {
    if (arr.length>2) {
      arr.splice((2*i), 1);
      }
     } 
  return arr
}

When invoked the function:

removeEveryOther(['1', '2', '3', '4', '5', '6', '7']) returns [ '2', '3', '5', '6' ]

Not sure what I'm doing wrong though, thanks for reading or even helping me out. Have a nice day!

6 Answers6

4

You can use filter. And move the check up to the top:

function removeEveryOther(arr){
  if (arr.length <= 2) {
    return arr
  }

  return arr.filter((a,i) => i%2 == 0);
}
Gh05d
  • 7,923
  • 7
  • 33
  • 64
1

You should not mutate the original array and rather create a new one.

function removeEveryOther(arr){
  if (arr.length > 2) {
    return arr.filter((item, index) => index % 2 === 0);
  } else {
    return arr;
  }
}
amik
  • 5,613
  • 3
  • 37
  • 62
1

you can do this:

let removeEvery2 = (arr) => {
    if(arr.length > 2) {
       return arr.filter((el, i) => i % 2 === 0)
    }
   return arr
}
Red Baron
  • 7,181
  • 10
  • 39
  • 86
1

You could loop from the end, because with splicing from start all following indices are gone.

function removeEveryOther(array) {
    if (array.length < 3) return array;

    let i = Math.floor(array.length / 2) * 2 + 1;
    while (i > 0) {
        array.splice(i, 1);
        i -= 2;
    }
    return array;
}

console.log(removeEveryOther([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])); // [1, 3, 5, 7, 9]
console.log(removeEveryOther([1, 2]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-2

Try this function, I kept it very simple for your understanding and very near to what you wrote in the question

function removeEveryOther(arr)
{
    if(arr.length <= 2)
        return arr;
     var arr_ret = [];
     for (i=0; i < arr.length; i+=2) 
     {
        arr_ret.push(arr[i])     
     } 
    return arr_ret
}
NoobX
  • 125
  • 6
-2

Use a simple for loop. Start at index 1 instead of 0 and increment i by 2 instead of 1.

function removeEveryOther(arr){
    if(arr.length <= 2) return arr;
    for(let i = 1; i < arr.length; i +=2){
        arr.splice(i, 1);
    }
    return arr;
}

console.log(removeEveryOther([1, 2, 3, 4, 5, 6, 7, 8]));
console.log(removeEveryOther([1, 2]))
bill.gates
  • 14,145
  • 3
  • 19
  • 47