Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are empty items in my array and how do I get rid of them? [duplicate]

I am using Visual Studio Code. I am trying to return an array with only odd numbers using JavaScript. This is the code:

function oddCouple(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 == 0) {
      delete arr[i];
    }
  }
  return arr;
}

console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));

This is what I am getting. I do not want the empty items, just odd numbers.

[ <2 empty items>, 7, <1 empty item>, 1, 3, 7, 5 ]
like image 562
ACF Avatar asked Mar 06 '23 16:03

ACF


2 Answers

You need to use splice() instead of delete because delete doesn't change the length of the array. But be careful using splice() in a for loop because you alter the array as you're looping through it, which doesn't work well.

An alternative is to loop backwards:

function oddCouple(arr) {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] % 2 == 0) {
      arr.splice(i, 1);
    }
  }
  return arr;
}

console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));

Of course a still better alternative is to use filter(), but note this doesn't change the original array.

function oddCouple(arr) {
  return arr.filter(i => i % 2)  
}

console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
like image 80
Mark Avatar answered Mar 08 '23 06:03

Mark


The delete function removes the content of the item but keeps an empty slot.

You need the splice method to remove an element without leaving an empty slot.

arr.splice(i, 1);
like image 31
f-CJ Avatar answered Mar 08 '23 06:03

f-CJ