revision:
The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
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.
array.filter(callbackFn)
array.filter(callbackFn, thisArg)
array.filter(function(currentValue, index, arr), thisValue)
Parameters:
callbackFn, function() : required; a function to run for each array element.It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments:
currentValue, element : required; the value of the current element; the current element being processed in the array.
index : optional; the index of the current element being processed in the array;
arr : optional; the array of the current element.
thisValue, thisArg: a value to use as "this" when executing callbackFn; an array, containing the elements that pass the test. If no elements pass the test it returns an empty array.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
example:
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>
example:
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>
example:
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>
example:
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>
example:
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>
example:
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>
example:
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>
example:
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>
example: filter ages
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 elemets 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>