.filter()

.filter()

  • Returns the value of the first element in the array that satisfies the provided testing function

  • undefined is returned if no element satisfies testing function

  • The callback function for .find() accepts the following parameters:

    • element: (required) current element being processed in the array.

    • index: (optional) index of the current element being processed in the array

    • array: (optional) the array map was called upon

  • .filter() returns a new array containing all elements that match the testing function


Syntax

Using traditional (ES5) function syntax

const result = arr.filter(function(item, index, array) {
  // if true is returned, item is returned and iteration is stopped
  // for falsy scenario returns undefined
})

Using arrow syntax (ES6)

const result = arr.filter((item, index, array) => {
  // if true is returned, item is returned and iteration is stopped
  // for falsy scenario returns undefined
})

Example

const numbers = [5, 3, 13, 4, 11 ]

const greaterThan5 = numbers.filter((number) => {
  return number > 5
})

console.log(greaterThan5) // [13, 11]

JS Bin on jsbin.com


Exercise

Use .filter() to return all words that have more than 6 characters in the words array.

Save the returned values to a variable declared with const called longWords

JS Bin on jsbin.com