DEV Community

Cover image for Filter: A JavaScript Iterator
Michellebuchiokonicha
Michellebuchiokonicha

Posted on • Updated on

Filter: A JavaScript Iterator

The filter iterator is similar to a map as it returns an array and does not change the original array as discussed in our last session. https://dev.to/michellebuchiokonicha/map-a-javascript-iterator-1oem

However, unlike a map, its callback must return an expression that evaluates to true or false. The new array is filtered and filled with elements that passed the true or false evaluation/test implemented by the provided function. Required parameters include function, current value, index, array, and value. The index, array, and value are optional but the function and current value are compulsory fields.

An example: let houseNumbers = [45, 66, 26, 92]; let highHouseNumbers = houseNumbers.filter(function(val){ return val > 45; } the result is : [66, 92];

Another example: var wordPlay = [mimi, cat, money, veggie] var newWords = wordPlay.filter(play =>play.length > 4); console.log(newWords) the result is: [money, veggie];

notice that here, I used a declarative function in the first example and an arrow function in the second example.

Both will produce the same result.

My Twitter Handle: https://twitter.com/mchelleOkonicha

My LinkedIn Handle: https://www.linkedin.com/in/buchi-michelle-okonicha-0a3b2b194/

Top comments (0)