Code has been added to clipboard!

Using JavaScript Filter to Match Values and Create New Arrays

Reading time 2 min
Published Feb 25, 2020
Updated Feb 25, 2020

TL;DR – JavaScript filter() function is for defining a new array with elements from the initial array that match a specified condition/function.

How the JavaScript array filter works

Developers create arrays to orderly store multiple elements in containers. There are various functions for sorting arrays (for example, changing the order of elements). However, the JS filter() method lets you filter elements according to specified conditions.

This code example illustrates how you can filter an array called fruits and create a new one, consisting only of names that have more than 6 characters.

Example
var fruits = ["Apple", "Blackcurrant", "Blueberries", "Banana", "Blackberries", "Plums"];
document.getElementById("test").innerHTML = fruits;
 
function myFunction() {
   var result = fruits.filter(word => word.length > 6);
   document.getElementById("test").innerHTML = result;

The next code example presents an array called prices. We are going to apply JavaScript filter() to create a new array with values that are less than 100:

Example
var prices = [15, 45, 1234, 65, 122, 555];
document.getElementById("test").innerHTML = prices;
 
function myFunction() {
   var result = prices.filter(price => price < 100);
   document.getElementById("test").innerHTML = result;
}

In the following example, we use JS filter() on an array of participants and filter them by their age. The name appears in the new array if the age is more than 18.

Example
var participants = [{ name: 'Anna', age: 19 },
{ name: 'Josh', age: 17 },
{ name: 'Mary', age: 15 },
{ name: 'Emily', age: 14 },
{ name: 'Caroline', age: 24 },
{ name: 'Sam', age: 16 }];
document.getElementById("test").innerHTML = participants.map(e => e.name + " -> " + e.age).join(', ');


function myFunction() {
    var result = participants.filter(participant => participant.age > 18);
    document.getElementById("test").innerHTML = result.map(e => e.name + " -> " + e.age).join(', ');
}

Syntax of JS filter()

The JavaScript filter() method has several components to its syntax.

newArray = initialArr.filter(callback);
  • newArray: you name the array that will consist of the filtered elements.
  • initialArr: the name of the original array.
  • callback: the method applied to the initialArr.

The callback can have three arguments as well:

  • element: the current element of the array.
  • index: the index number of the currently handled value.
  • array: the original array.

Therefore, the full syntax of the JavaScript array filter function would look like this:

newArray = initialArr.filter(callback(element, index, array));

Note: the JavaScript filter() does not affect the initial array. It applies the callback function to every element to create a new collection with filtered elements.

JavaScript filter: useful tips

  • jQuery library also has a filter() function for filtering values according to specified conditions. It offers a not() method which returns values that do not match the condition.
  • The JavaScript array filter function is closely related to map, push and length methods. These functions will give you more control over your arrays and contribute to the production of shorter code.
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Math.random()
Type Conversion
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen