Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove null values from array using Array.indexOf?

I'm trying to find if there's a null value in my array without using for loops, mainly something similar to Array.indexOf. Undefined is NOT a string, it's a null value that comes up as undefined when I use console.log(ARRPREFIX)

var arr = ["**", undefined, null];
if (arr.indexOf(null) > -1) {
  console.log("Should be null");
  arr.splice(arr.indexOf(null), 1);
}

Above is my code, however it doesn't detect the undefined value, I also tried putting in "undefined" instead but that doesn't work.

like image 300
Mad_ Questionnaire Avatar asked Oct 20 '25 11:10

Mad_ Questionnaire


1 Answers

You can use filter to filter out falsy values (null, undefined, etc):

var array = [2, 3, null, 4, undefined, 5];
array = array.filter(Boolean);

console.log(array);
like image 73
Alberto Trindade Tavares Avatar answered Oct 22 '25 23:10

Alberto Trindade Tavares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!