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.
asked Jul 10, 2017 at 11:19
Mad_ Questionnaire
1,0233 gold badges11 silver badges11 bronze badges
2 Answers 2
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);
answered Jul 10, 2017 at 11:20
Alberto Trindade Tavares
10.5k6 gold badges42 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
10 Comments
abhishekkannojia
what about
undefined ?Alberto Trindade Tavares
See my edited answer. Just fixed to handle undefined also
Jamiec
And did you notice the undefined is not actually
undefinedAlberto Trindade Tavares
I considered undefined, and not "undefined". If you want to filter out the string "undefined", it is just a matter of adjusting the filter
abhishekkannojia
You can shorten it removing inner function to filter:
array.filter(Boolean) |
I think those javascript array functions use loops on background anyway.
2 Comments
Mad_ Questionnaire
The point is I don't want to loop through my entire array and delete null/undefined values, since overtime it will get bigger so for loops just won't do.
azurinko
Those functions are going to be executed anyway, how do you thing array functions work? You can't get value of it without looping trought array. Index of is going to do that anyway...
lang-js
null≠undefined≠"undefined"undefined. It's as far from undefined as undefined can bearr.filter(Boolean)It should remove falsy values