4

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.

4
  • 3
    nullundefined"undefined" Commented Jul 10, 2017 at 11:21
  • 1
    You dont have an "undefined value", you have a string which so happens to have the characters undefined. It's as far from undefined as undefined can be Commented Jul 10, 2017 at 11:22
  • 1
    undefined is not the actual string undefined, it's a null value that comes up as undefined when I use console.log(ARRPREFIX) to print the array. Commented Jul 10, 2017 at 11:29
  • Just use arr.filter(Boolean) It should remove falsy values Commented Jul 10, 2017 at 11:32

2 Answers 2

8

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);

Sign up to request clarification or add additional context in comments.

10 Comments

what about undefined ?
See my edited answer. Just fixed to handle undefined also
And did you notice the undefined is not actually undefined
I considered undefined, and not "undefined". If you want to filter out the string "undefined", it is just a matter of adjusting the filter
You can shorten it removing inner function to filter: array.filter(Boolean)
|
-2

I think those javascript array functions use loops on background anyway.

2 Comments

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.
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.