JavaScript Glossary - Lesson #4

JavaScript Array .filter() Method

The filter() method returns an array containing elements of the parent array that match the set test. A function containing a test is passed as an argument to the filter method. To keep an element the test function should return true and false to discard an element.

js
[10, 2, 5, 100, 8].filter((number)=> number < 20) // filter array for numbers less than 20
js
// We have an array with numbers
const numbers = [2, 4, 6, 8, 32, 100]

// Create function to filter any array
const functionToFilterNumbers = function(number){
    return number > 5;
}

// Filter the 'numbers' array
const filtered = numbers.filter(functionToFilterNumbers)

//Display filtered array
console.log(filtered) // [6,8,32,100]

The filter method:

  • Will take a test function
  • Returns a new array containing the elements that matches the set test
  • Returns an empty array if there are no matches
js
const filteredArray = oldArray.filter(callbackFunction(element[,index[,array]])[, thisArg])

callbackFunction The function that executes each of the elements of the array. The callback function is required and can take three parameters - required.

element This is the element currently being executed - required.

index This is the index of the current item - optional.

array This is the array that is currently being processed - optional.

thisArg This is an argument passed to be used as the this value in the callback - optional

A new array is returned and this doesn't change the value of the old array.

js
// create an array
const names = ['John', 'Peter', 'James', 'Pammy'];

// Filter the array for names having 'am'
const myName = names.filter(name => name.includes('am'));

// Output new array
console.log(myName)

Processing an array of numbers and returning the numbers that are within a set range. e.g: Checking if a person is old enough to watch the Deadpool movie.

js
// Create new array
const ages = [14, 12, 18, 21, 10];

// filter array for numbers in a range
const canSeeDeadpool = ages.filter(function(age){
  return age >= 18;
})

// display new filtered array
console.log(canSeeDeadpool); // [18,21]

The .filter() method can be used to filter an array of objects which share a similar property. E.g Getting the students that passed a set.

js
// Create array of students
const students = [
  {
    name: 'Peter',
    score: 50
  },
  {
    name: 'Sarah',
    score: 40
  },
  {
    name: 'Andy',
    score: 33
  },
  {
    name: 'Grace',
    score: 60
  }
]

// Filter array for students who passed a score from 50 and above
const studentsThatPassed = students.filter(function(student){
  return student.score >= 50
})

// Display new students in an array
console.log(studentsThatPassed) // [{"name":"Peter","score":50},{"name":"Grace","score":60}]

Another use of the .filter() method is filter out array entries beyond a particular array index.

js
// Create array of continents
const places = ['Africa', 'Asia', 'Europe', 'Australia'];

// Filter array for continents beyond the array index of 1
const overIndex = places.filter(function(place, index){
  return index > 1;
})

// Display new Array
console.log(overIndex); // ["Europe","Australia"]

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)