JavaScript - filter()

revision:


Content

The filter() method creates a new array filled with elements that pass a test. How JavaScript's filter() works Some more examples restaurants


The filter() method creates a new array filled with elements that pass a test.

top

The test is provided by a function. However, the filter() method does not execute the function for empty elements, and it does not change the original array.

Syntax: array.filter(function(currentValue, index, arr), thisValue)

Parameters:

function() : required; a function to run for each array element.

currentValue : required; the value of the current element;

index : optional; the index of the current element;

arr : optional; the array of the current element.

return value: an array, containing the elements that pass the test. If no elements pass the test it returns an empty array.


How JavaScript's filter() works

top

prior to ES6

numbers: 20, 40, 17, 99, 59, 77

code:
                <div>
                    <p>numbers: 20, 40, 17, 99, 59, 77</p>
                    <p id="filtered1"></p>            
                </div>
                <script>
                    const numbers = [20, 40, 17, 99, 59, 77];
                    const filteredNumbers = numbers.filter(function (number) {
                    return number > 20;
                    });
                    document.getElementById("filtered1").innerHTML = "filtered numbers: " + filteredNumbers;
                </script>

            

since ES6, an arrow function can be used

numbers: 20, 40, 17, 99, 59, 77

code:
                <div>
                    <p>numbers: 20, 40, 17, 99, 59, 77</p>
                    <p id="filtered2"></p>            
                </div>
                <script>
                    const numbersA = [20, 40, 17, 99, 59, 77];
                    const filteredNumbersA = numbers.filter((number) =>{
                    return number > 20;
                    });
                    document.getElementById("filtered2").innerHTML = "filtered numbers: " + filteredNumbersA;
                </script>
            

menu list

filter menu list

code:
                <div>
                    <p id="menu"></p>
                </div>
                <script>
                    const menu = [
                        {name: "buttermilk pancakes", price: 15.99 },
                        {name: "diner double", price: 13.99},
                        {name: "godzilla milkshake", price: 6.99},
                        {name: "country delight", price: 20.99},
                        {name: "egg attack", price: 22.99}
                    ];
                    let priceRange = {
                        lower: 15,
                        upper: 25
                    };
                    let filteredMenu = menu.filter(function (menu) {
                        return menu.price >= this.lower && menu.price <= this.upper;
                    }, priceRange);
                    document.getElementById("menu").innerHTML = JSON.stringify(filteredMenu); 
                </script>
            

using the index parameter

code:
                <div>
                    <p id="users_A"></p>
                </div>
                <script>
                    const users_A = ["John", "Doe", "Stephen", "Matt", "Abigail", "Susu"];
                    const topThree = users_A.filter((element, index) => {
                        return index <= 2;
                    });
                    document.getElementById("users_A").innerHTML = topThree; 
                </script>
            

using the array parameter

code:
                <div>
                    <p id="users_B"></p>
                </div>
                <script>
                    const users_B = ["John", "Doe", "Stephen", "Matt", "Abigail", "Susu"];
                    function selectWinners(name, index, array) {
                        if (array.length > 3 && name.includes('a')) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    let selectLoosers = users_B.filter((name, index, array) =>
                        selectWinners(name, index, array)
                    );
                    document.getElementById("users_B").innerHTML = selectLoosers; 
                
                </script>
            

menu list - second

code:
                <div>
                    <p id="menu2"></p>
                </div>
                <script>
                    const menu2 = [
                        { name: "buttermilk pancakes", category: "breakfast", price: 15.99, status: "available"},
                        { name: "diner double", category: "lunch", price: 13.99, status: "available" },
                        { name: "godzilla milkshake", category: "shakes", price: 6.99, status: "available"},
                        { name: "country delight", category: "breakfast", price: 20.99, status: "86"},
                        { name: "egg attack", category: "lunch", price: 22.99, status: "available"                }
                    ];
                    let breakfastMenu = menu2.filter((menu2) => menu2.category === "breakfast");  
                    document.getElementById("menu2").innerHTML = JSON.stringify(breakfastMenu);
                    console.log(breakfastMenu);

                </script>
            

filter out items based on a property

code:
                <div>
                    <p id="proper"></p>
                    <p id="proper2"></p>
                </div>
                <script>
                    let team = [
                        {name: "Aaron", position: "developer" },
                        {name: "Beth", position: "ui designer"},
                        {name: "Cara", position: "developer"},
                        {name: "Daniel", position: "content manager"},
                        {name: "Ella", position: "cto"},
                        {name: "Fin", position: "backend engineer"},
                        {name: "George", position: "developer"},
        
                    ]
                    let developers = team.filter(member => member.position == "developer")
                    document.getElementById("proper").innerHTML = "developers: " + JSON.stringify(developers);
                    console.log(developers);
                    let nondevelopers = team.filter(member => member.position !== "developer")
                    document.getElementById("proper2").innerHTML = "non-developers: " + JSON.stringify(nondevelopers);
                    console.log(nondevelopers);
                </script>
            

access the context object with "this"

code:
                <div>
                    <p id="people"></p>
                </div>
                <script>
                    let people = [
                        {name: "aaron", age: 65},
                        {name: "beth", age: 15},
                        {name: "cara", age: 13},
                        {name: "daniel", age: 3},
                        {name: "ella", age: 25},
                        {name: "fin", age: 16},
                        {name: "george", age: 18},
                    ]
                    let range = {
                    lower: 13,
                    upper: 16
                    }
                    let teenagers = people.filter(function(person) {
                        return person.age >= this.lower && person.age <= this.upper;
                    }, range)
                    document.getElementById("people").innerHTML = JSON.stringify(teenagers);
                    console.log(teenagers)
        
                </script>
            


Some more examples

top

example: filtered array

code:
                <div>
                    <p id="filter-A"></p>
                    <p id="filter-B"></p>
                </div>
                <script>
                    const Leeftijd = [32, 33, 16, 40, 10, 15, 50];
                    document.getElementById("filter-A").innerHTML = "original array: " + Leeftijd;
                    document.getElementById("filter-B").innerHTML = "filtered array: " + Leeftijd.filter(checkAdult);
        
                    function checkAdult(leeftijd) {
                        return leeftijd >= 18;
                    }
                </script>

            

example: filter purchases

purchase (in Euros): 2.50, 2.70, 10.50, 7.5, 12.30, 9.60, 2.30, 3.40, 11.5, 6.7, 10

code:
                <div class="spec">
                    <p>purchase (in Euros): 2.50, 2.70, 10.50, 7.5, 12.30, 9.60, 2.30, 3.40, 11.5, 6.7, 10</p>
                    <p id="filter1"></p>
                    <p id="filter2"></p>
                    <p id="filter3"></p>
                </div>
                <script>
                    var purchases = [2.50, 2.70, 10.50, 7.5, 12.30, 9.60, 2.30, 3.40, 11.5, 6.7, 10];
                    var big_purchases = purchases.filter(function(purchase) {
                        return purchase > 10;
                    });
                    document.getElementById("filter1").innerHTML = "  - big purchases (in Euros) are: " + big_purchases;
                    
                    var small_purchases = purchases.filter(function(purchase) {
                        return purchase < 5;
                    });
                    document.getElementById("filter2").innerHTML = "  - small purchases (in Euros) are: " + small_purchases;
                    
                    var medium_purchases = purchases.filter(function(purchase) {
                        return purchase > 5 && purchase < 10;
                    });
                    document.getElementById("filter3").innerHTML = "  - medium purchases (in Euros) are: " + medium_purchases;
                </script>
            

example: select words by length.

array of words: spray, limit, elite, exuberant, destruction, present, absentee

click the button to filter the words longer than six characters.

Click the button to filter the words shorter than six characters.

code:
                <div class="spec">
                    <p>array of words: spray, limit, elite, exuberant, destruction, present, absentee</p>
                    <p>click the button to filter the words longer than six characters.</p>
                    <button onclick="orderWords()">try it</button>
                    <p style="color:red" id="filterA"></p>
                    <p>Click the button to filter the words shorter than six characters.</p>
                    <button onclick="orderWords1()">try it</button>
                    <p style="color:red"  id="filterB"></p>
                </div>
                <script>
                    var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present', 'absentee'];
                    function orderWords() {
                        var result = words.filter(word => word.length > 6);
                        document.getElementById("filterA").innerHTML = result;
                    }
                    function orderWords1() {
                        var result1 = words.filter(word => word.length < 6);
                        document.getElementById("filterB").innerHTML = result1;
                    }
                </script>   
            

example: get elements by value

array: 32, 33, 12, 44, 40, 10, 16, 21, 34, 2

click the button to get every element in the array that has a value above this number.

code:
                <div>
                    <p class="spec">Array: 32, 33, 12, 44, 40, 10, 16, 21, 34, 2</p>
                    <p class="spec">Click the button to get every element in the array that has a value above this number.</p>
                    <p class="spec"><input type="number" id="ageToCheck" value="18"></p>
                    <button onclick="myFunction()">try it</button>
                    <p class="spec" id="filter6"></p>
                </div>    
                <script>
                    const ages = [32, 33, 12, 44, 40, 10, 16];
                    function checkAge(age) {
                        return age > document.getElementById("ageToCheck").value;
                    }
                    function myFunction() {
                        document.getElementById("filter6").innerHTML = ages.filter(checkAge);
                    }
                </script>
            

example: select students by grade

code:
                <div class="spec">
                    <p class="spec" id="list"></p> 
                    <button onclick="firstGrade()">first grade</button>
                    <p class="spec" id="filter4"></p>
                    <button onclick="secondGrade()">second grade</button>
                    <p class="spec" id="filter5"></p> 
                    <button onclick="thirdGrade()">third grade</button>
                    <p class="spec" id="filter5A"></p> 
                </div>    
                <script>
                    var students = [
                        { id: 1, name: "Alex",  class: "first grade", age: 5},
                        { id: 2, name: "Bill",  class: "first grade", age: 5},
                        { id: 3, name: "Connor", class: "second grade", age: 6},
                        { id: 4, name: "Aron", class: "third grade", age: 7},
                        { id: 5, name: "Bernd", class: "first grade", age: 5},
                        { id: 6, name: "Carl", class: "second grade", age: 6}];
                    document.getElementById("list").innerHTML = "Students: " + students.map(e => e.name + " , " + 
                    e.class + " , " + e.age).join(';   ');
        
                    function firstGrade() {
                        var resultaat = students.filter(student => student.class === "first grade");
                        document.getElementById("filter4").innerHTML = resultaat.map(e => e.name + " : " + e.class).join(', ');
                    }
                    function secondGrade() {
                        var resultaat_1 = students.filter(student => student.class === "second grade");
                        document.getElementById("filter5").innerHTML = resultaat_1.map(e => e.name + " : " + e.class).join(', ');
                    }
                    function thirdGrade() {
                        var resultaat_2 = students.filter(student => student.class === "third grade");
                        document.getElementById("filter5A").innerHTML = resultaat_2.map(e => e.name + " : " + e.class).join(', ');
                    }
                </script>
            

example: filter array by age.

click the button to filter by age.

code:
                <div>
                    <p class="spec">Click the button to filter by age.</p>
                    <p class="spec" id="test"></p>
                    <button onclick="orderAge()">older than 18</button>
                    <p class="spec" id="filter7"></p>
                    <button onclick="orderAge1()">younger than 18</button>
                    <p class="spec" id="filter8"></p>
                </div>
                <script>
                    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 orderAge() {
                        var result = participants.filter(participant => participant.age >= 18);
                        document.getElementById("filter7").innerHTML = result.map(e => e.name + " : " + e.age).join(', ');
                    }
                    function orderAge1() {
                        var result = participants.filter(participant => participant.age < 18);
                        document.getElementById("filter8").innerHTML = result.map(e => e.name + " : " + e.age).join(', ');
                    }
                </script>
            

example: filter array by department

click the button to filter by department.

code:
                <div>
                    <p class="spec" id="testA"></p>
                    <p class="spec">click the button to filter by department.</p>
                    <button onclick="selectDep()">IT department</button>
                    <p class="spec" id="filter9"></p>
                    <button onclick="otherDep()">other departments</button>
                    <p class="spec" id="filter10"></p>
                </div>    
                <script>
                    var employees = [
                        {name: "Tony Stark", department: "IT"},
                        {name: "Peter Parker", department: "Pizza Delivery"},
                        {name: "Bruce Wayne", department: "IT"},
                        {name: "Clark Kent", department: "Editing"}
                        ];
                    document.getElementById("testA").innerHTML = employees.map(e => e.name + " : " + e.department).join(', ');
                    function selectDep() {
                        var output =  employees.filter(employee => employee.department == "IT");
                            for(var i=0;i<output.length;i++){
                                document.getElementById("filter9").innerHTML = output.map(e => e.name + " : " + e.department).join(', ');
                            };
                    }
                    function otherDep() {
                        var output =  employees.filter(employee => employee.department != "IT");
                        for(var i=0;i<output.length;i++){
                                document.getElementById("filter10").innerHTML = output.map(e => e.name + " : " + e.department).join(', ');
                            };
                    }
                </script>
            

example: filter array by habitat

code:
                <div class="spec">
                    <p id="habitat"></p>
                </div>
                <script>
                    var creatures = [
                        {name: "Shark", habitat: "Ocean"},
                        {name: "Whale", habitat: "Ocean"},
                        {name: "Lion", habitat: "Savanna"},
                        {name: "Monkey", habitat: "Jungle"}
                    ];
                    var aquaticCreatures =  creatures.filter(function(creature) {
                        return creature.habitat == "Ocean"; 
                    });
                    document.getElementById("habitat").innerHTML = JSON.stringify(aquaticCreatures);
                </script>
            

combined examples




code:
                <div class="spec">
                    <p id="combination"></p>
                    <p id="combination-a"></p><br>
                    <p id="combination-b"></p>
                    <p id="combination-c"></p>
                    <p id="combination-d"></p>
                    <p id="combination-e"></p><br>
                    <p id="combination-f"></p>
                    <p id="combination-g"></p>
                    <p id="combination-h"></p><br>
                    <p id="combination-i"></p>
                    <p id="combination-j"></p>
                    
            
                </div>
                <script>
                    let numbers_aa = [1, 2, 3, 4, 5];
                    document.getElementById('combination').innerHTML = "original array: " + numbers_aa;
                    let evenNumbers = numbers_aa.filter(number_aa => number_aa % 2 === 0);
                    document.getElementById('combination-a').innerHTML = "even numbers: " + evenNumbers;
            
                    let numbers_ab = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                    document.getElementById('combination-b').innerHTML = "original array: " + numbers_ab;
                    let filteredNumbers_ab = numbers_ab.filter(number_ab => number_ab > 5);
                    document.getElementById('combination-c').innerHTML = "numbers greater than 5: " + filteredNumbers_ab;
                    let filteredAndMappedNumbers = numbers_ab.filter(number_ab => number_ab > 5).map(number_ab => number_ab * 2);
                    document.getElementById('combination-d').innerHTML = "numbers after combining filter with map: " + filteredAndMappedNumbers;
                    let sumOfFilteredNumbers = numbers_ab.filter(number_ab => number_ab > 5).reduce((sum, number_ab) => sum + number_ab, 0);
                    document.getElementById('combination-e').innerHTML = "sum of numbers greater than 5 (using reduce()): " + sumOfFilteredNumbers;
            
                    let numbers_ac = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                    document.getElementById('combination-f').innerHTML = "original array: " + numbers_ac;
                    let filteredNumbers_ac = numbers_ac.reduce((accumulator, number_ac) => {
                        if (number_ac > 5) {
                            accumulator.push(number_ac);
                        }
                        return accumulator;
                    }, []);
                    document.getElementById('combination-g').innerHTML = "filtered numbers : " + filteredNumbers_ac;
                    let filteredNumbers_ad = [];
                    for (let i = 0; i < numbers_ac.length; i++) {
                        if (numbers_ac[i] > 5) {
                            filteredNumbers_ad.push(numbers_ac[i]);
                        }
                    }
                    document.getElementById('combination-h').innerHTML = "filtered numbers : " + filteredNumbers_ad;
            
                    let numbers_ae = [1, 2, 3, 4, 5];
                    document.getElementById('combination-i').innerHTML = "original array: " + numbers_ae;        
                    let filteredNumbers_ae = numbers_ae.filter(number_ae => number_ae > 10);
                    if (filteredNumbers_ae.length === 0) {
                        document.getElementById("combination-j").innerHTML = 'no numbers passed the test';
                    } else {
                        document.getElementById("combination-j").innerHTML = 'filtered numbers' + filteredNumbers_ae;;
                    }
                </script>
            

restaurants

top

All Restaurants

Burger Joints

Pizza Joints

Tex-Mex Joints

Cheap Joints

Moderately Priced Joints

Expensive Joints

code:
            <div class="restaurant grid3">
                <div>
                    <h4>All Restaurants</h4>
                    <ul id='restaurants'></ul>
                </div>
                <div>
                    <h4>Burger Joints</h4>
                    <ul id='burgerJoints'></ul>
                </div>
                <div>
                    <h4>Pizza Joints</h4>
                    <ul id='pizzaJoints'></ul>
                </div>
                <div>
                    <h4>Tex-Mex Joints</h4>
                    <ul id='texMexJoints'></ul>
                </div>
                <div>
                    <h4>Cheap Joints</h4>
                    <ul id='cheapJoints'></ul>
                </div>
                <div>
                    <h4>Moderately Priced Joints</h4>
                    <ul id='moderateJoints'></ul>
                </div>
                <div>
                    <h4>Expensive Joints</h4>
                    <ul id='expensiveJoints'></ul>
                </div>
            </div>
            <style>
               .restaurant *:before, *:after {box-sizing: border-box; margin: 0; padding: 0;}
               .restaurant{margin: 0; padding: 1rem; font-size: 16px; line-height: 1.4;  font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;}
            </style>
            <script>
                const restaurants = [
                    {name: "Dan's Hamburgers", price: 'Cheap', cuisine: 'Burger',},
                    {name: "Austin's Pizza", price: 'Cheap', cuisine: 'Pizza',},
                    {name: "Via 313", price: 'Moderate', cuisine: 'Pizza',},
                    {name: "Bufalina", price: 'Expensive', cuisine: 'Pizza',},
                    {name: "P. Terry's", price: 'Cheap', cuisine: 'Burger',},
                    {name: "Hopdoddy", price: 'Expensive', cuisine: 'Burger',},
                    {name: "Whataburger", price: 'Moderate', cuisine: 'Burger',},
                    {name: "Chuy's", cuisine: 'Tex-Mex', price: 'Moderate',},
                    {name: "Taquerias Arandina", cuisine: 'Tex-Mex', price: 'Cheap',},
                    {name: "El Alma", cuisine: 'Tex-Mex', price: 'Expensive',},
                    {name: "Maudie's", cuisine: 'Tex-Mex', price: 'Moderate',},
                ];
                
                    const isKeyEqualToValue = key => value => object => object[key] === value;
                    const isPrice   = isKeyEqualToValue('price');
                    const isCuisine = isKeyEqualToValue('cuisine');
        
                    const isBurger    = isCuisine('Burger');
                    const isPizza     = isCuisine('Pizza');
                    const isTexMex    = isCuisine('Tex-Mex');
        
                    const isCheap     = isPrice('Cheap');
                    const isModerate  = isPrice('Moderate');
                    const isExpensive = isPrice('Expensive');
        
                    renderList(restaurants, 'restaurants'); 
                    renderList(restaurants.filter(isBurger), 'burgerJoints');
                    renderList(restaurants.filter(isPizza), 'pizzaJoints');
                    renderList(restaurants.filter(isTexMex), 'texMexJoints');
        
                    renderList(restaurants.filter(isCheap), 'cheapJoints');
                    renderList(restaurants.filter(isModerate), 'moderateJoints');
                    renderList(restaurants.filter(isExpensive), 'expensiveJoints');
        
                    // simple rendering function
                    function renderList (restaurantList, listId) {
                    const list = document.getElementById(listId);
                    
                    const listItems = restaurantList.map(({name}) => {
                        const item = document.createElement('li');
                        item.innerText = name;
                        return item;
                    })
                    
                    listItems.forEach(listItem => {
                        list.append(listItem);
                    })
                    }
        
            </script>