w3resource

JavaScript: Find all indexes of NaN in an array

JavaScript Array: Exercise-52 with Solution

Write a JavaScript program to get all the indexes where NaN is found in a given array of numbers and NaN.

Test Data:

([2, NaN, 8, 16, 32]) -> [1]
([2, 4, NaN, 16, 32, NaN]) -> [2,5]
([2, 4, 16, 32]) ->[]

Sample Solution:

JavaScript Code :

// Function to find all indexes of NaN in an array
function test(arr_nums){
    // Use map to create an array of indexes where NaN is found, otherwise return false
    return arr_nums.map(function(el, i){
        if(isNaN(el)) 
          return i;
        return false;
    })
    // Use filter to remove falsy values (non-NaN elements)
    .filter(function(el){
        return el;
    });
}

// Test the function with an array containing NaN at multiple indexes
arr_nums = [2, NaN, 8, 16, 32];
console.log("Original array: "+arr_nums);
result = test(arr_nums);
console.log("Find all indexes of NaN in the said array: "+result);

// Test the function with another array containing NaN at multiple indexes
arr_nums = [2, 4, NaN, 16, 32, NaN];
console.log("Original array: "+arr_nums);
result = test(arr_nums);
console.log("Find all indexes of NaN in the said array: "+result);

// Test the function with an array without NaN
arr_nums = [2, 4, 16, 32];
console.log("Original array: "+arr_nums);
result = test(arr_nums);
console.log("Find all indexes of NaN in the said array: "+result);

Output:

Original array: 2,NaN,8,16,32
Find all indexes of NaN of the said array: 1
Original array: 2,4,NaN,16,32,NaN
Find all indexes of NaN of the said array: 2,5
Original array: 2,4,16,32
Find all indexes of NaN of the said array: 

Flowchart :

JavaScript array flowchart: Find all indexes of NaN in an array.

Live Demo :

See the Pen javascript-array-exercise-52 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous:Check if an array is a factor chain.
Next: Number of arrays inside an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-array-exercise-52.php