Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  64] [ 6]  / answers: 1 / hits: 63767  / 9 Years ago, mon, august 10, 2015, 12:00:00

I was asked to filter out NaN, null, 0, false in an array.



Luckily I have answered the question.



function bouncer(arr) {
function filterer(arr) {
return arr > 0|| isNaN(arr) === true;
}
arr = arr.filter(filterer);
return arr;
}

//example input
bouncer([0, 1, 2, 3, 'ate', '', false]); //output [1, 2, 3, 'ate']


but the thing is I really don't know how I came up with the answer or rather I don't know how it works. Specially on arr > 0 how did the filter know that arr is alread on arr[1], arr[2], etc.. without using a loop to iterate in all array.



or can simply just explain on how to code works. [I've tried to explain it clearly ---]


More From » arrays

 Answers
7

Look at the docs for Array.filter. Notice in particular the arguments to the callback:




Function to test each element of the array. Invoked with arguments (element, index, array). Return true to keep the element, false otherwise.




So in your case arr is the element (and poorly named, hence your confusion). Filter loops through your array and for every item it calls you callback passing in the element at the current position as arr.



As others have pointed out in the comments, the logic of your filter callback is actually flawed for negative values, but that may not be an issue if you know that your array will never contain negative values (but that can be a dangerous thing to assume).



And, of course, internally, this is looping through your array. You can't filter your (unsorted) array without touching each element in the array. Look at the polyfil in the link to get an idea of how it might work (might because this is an implementation detail that may differ with different javascript engines, but will no doubt involve a loop somewhere), it loops through your array, calls the callback (note the arguments) and if the callback returns true, it gets pushed onto a results array.


[#65461] Friday, August 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chelseyn

Total Points: 36
Total Questions: 85
Total Answers: 89

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;