How to remove specific values from a JavaScript array?

I’m working on a script to clean up an array by getting rid of zeros, empty strings, null, and undefined values. But I’m running into a problem. When I test it with [1,null,2,3,0,-1,1.1], the null and 0 are still there. Here’s my code:

function cleanUpList(list) {
  for (let i = 0; i < list.length; i++) {
    if (list[i] === 0 || list[i] === '' || list[i] === null || list[i] === undefined) {
      list.splice(i, 1);
      i--;
    }
  }
  return list;
}

What am I doing wrong? How can I fix this to remove all the unwanted values? Thanks for any help!

I’ve dealt with similar issues before, and I found that using the Array.filter() method is indeed more reliable than splicing. However, if you want to stick with your current approach, you might want to consider using a while loop instead. Here’s an alternative that worked well for me:

function cleanUpList(list) {
  let i = 0;
  while (i < list.length) {
    if (list[i] === 0 || list[i] === '' || list[i] == null) {
      list.splice(i, 1);
    } else {
      i++;
    }
  }
  return list;
}

This way, you only increment the index when you don’t remove an element. It’s a bit more verbose, but it handles the shifting indices problem that comes with splicing in a for loop. Give it a try and see if it solves your issue.

hey stella, ur code looks alright but splice can be tricky. try using filter instead. it’s easier and won’t mess up ur loop:

function cleanUpList(list) {
  return list.filter(item => item !== 0 && item !== '' && item != null);
}

this should do the trick for ya. let me kno if it works!

I’ve encountered this issue before, and I can confirm that using Array.filter() is indeed the most elegant solution. However, if you’re set on modifying the original array, you might want to consider using the Array.reduce() method. It’s efficient and avoids the pitfalls of splicing while iterating:

function cleanUpList(list) {
  return list.reduce((acc, val) => {
    if (val !== 0 && val !== '' && val != null) {
      acc.push(val);
    }
    return acc;
  }, []);
}

This approach creates a new array with only the desired elements, which can be more performant for larger datasets. It’s also easier to read and maintain in the long run. Give it a shot and see if it meets your needs.