38
loading...
This website collects cookies to deliver better user experience
filter()
and reduce()
methods. For the purpose of today. I will focus more on filter()
.filter()
method extracts elements from an array that passes the test executed by the function and returns a new array with the values added.elements
in the array where the color's word length is equal to or larger than 6. Well, we can solve that by using the filter()
method.let colors = ['blue', 'red', 'orange', 'yellow', 'green', 'black', 'white', 'purple']
let passTest = colors
.filter(word => word.length >= 6)
console.log(passTest)
//output: ["orange", "yellow", "purple"]
filter()
method on colors
array and with our function pass in an element, which in this case is word
and return the word
that coerces to true
, to keep the element.console.log(passTest)
, you'll see the words that passed the function's test. ["orange", "yellow", "purple"]
colors
from above. Instead of word length, let's search for the word that has the letters low
and return that word. We can continue to utilize filter()
to solve this problem.let colors = ['blue', 'red', 'orange', 'yellow', 'green', 'black', 'white', 'purple']
function search(arr, query){
return arr.filter(function(str){
return str.indexOf(query) !== -1
})
}
console.log(search(colors, "low"))
//output: ["yellow"]
arr
, the second being the query
(a string). return arr.filter(function(str){
})
str
which the inner return statement will use.return str.indexOf(query) !== -1
element
in the array and using the indexOf
method to return the index of the given query
and compares it. If true
, it will return the element's word.console.log(search(colors, "low"))
to test it.filter()
is as follows:array.filter(function callbackFn(element, index, array))
callbackFn
function is the argument that test each element in the array. If true
keep the element. If false
do not keep. If no elements pass the test, there will be an empty array.index
and array
are optional.filter()
method is a great tool for filtering out elements from an array that passes a test (provided as a function). It then returns those values into a new array and thus does not mutate the original array.