Updated March 13, 2023
Introduction to JavaScript Filter Function
While manipulating a list or Array, we often face a situation where we have to filter out the results depending on some condition. For example, while online shopping, we can apply the filter on categories, brands, colors, sizes, etc., to retrieve the options that consider our requirements. In javascript, we can filter out the results based on some test conditions using the filter function provided by Array.prototype.filter().
The filter function creates a new array containing all the elements which satisfy the test condition, which is provided with the help of the function and is present in the supplied Array or list. Note that the original Array supplied for filtering is not affected here, and a new one is created with all the desired elements.
Syntax:
let desiredArray = originalArray.filter(callback(element[, currentIndex[, array]])[, thisArgument])
Explanation:
- callback: This is the first parameter which is a function that is a predicate that returns true if we want that particular element in the desired Array; else false.
- element: This is the second parameter, the element of the original Array currently being processed.
- currentIndex: The parameter specifies the index of the current element being processed.
- array: It is the Array on which we are applying the filter.
- thisArgument: This is the value that is to be used as this value in the callback function
- desiredArray: This is the return value of the filter function, an array containing all the elements that have succeeded the test or condition specified in the callback. It is completely a new array that is created.
Working of JavaScript Filter Function
The filter() function calls the callback function every time for every element in the Array to check whether it satisfies the predicate or condition specified in the callback and prepares a new array in which it inserts all the elements which have passed the test that is which have returned true when putting into the predicate. It only considers the Array of elements to which some value is assigned. Non-assigned or deleted elements are not considered, and their callback is invoked for such indexes. The elements which return false and fail the test of the callback function are skipped and not added to the resultant Array.
The callback function uses three arguments – the value of the array element, index of an array element, and original array object on which filter is to be performed and which is going to be traversed. If this argument is specified while using a filter, then the callback function considers the passed argument as this value; otherwise, undefined is considered this value. The value which is finally used is determined using the usual rules. Refer https://developer.mozilla.org/en-US/ docs/Web/JavaScript/Reference/Operators/this for further information about this value usage by a function.
The filter function never modifies the original Array passed for filtration. At the beginning of the invocation, the range of elements that will be processed is decided. If we add the elements to the Array after the filter function is called, those elements will not be considered for filtration. Also, suppose the value of the elements is modified or deleted. In that case, the value will be considered depending on when the filter function will call the callback event for that particular element. The deleted elements are never considered for filtration and are never visited by the callback function.
Examples of JavaScript Filter Function
Examples of javascript filter functions are given below:
Example #1
Let us understand its works with the help of an example.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Demonstration of filter function used in array to get all the words whose length is greater that five.</p>
<button onclick="sampleFunction()">Get Result</button>
<p>Array before performing filter operation</p>
<p id="beforeResult"></p>
<p>Resultant array after filtering the words whose length is greater that five</p>
<p id="sampleResult"></p>
<script>
function sampleFunction() {
const sampleWords = ['morning', 'afternoon', 'evening', 'night', 'educba', 'javascript']; document.getElementById("beforeResult").innerHTML =sampleWords;
const resultantArray = sampleWords.filter(currentWord => currentWord.length > 5); document.getElementById("sampleResult").innerHTML =resultantArray;
}
</script>
</body>
</html>
Output:
Example #2
Let us see one more example to filter out all the valid identifiers which can be used as id.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Demonstration of filter function used in array to get all the invalid identifiers.</p>
<button onclick="sampleFunction()">Get Result</button>
<p id="sampleResult1"></p>
<p id="sampleResult2"></p>
<p id="sampleResult3"></p>
<script>
function sampleFunction() {
let sampleArray = [
{ uniqueIdentifier: 98 },
{ uniqueIdentifier: -1 },
{ uniqueIdentifier: 0 },
{ uniqueIdentifier: 3 },
{ uniqueIdentifier: 12.2 },
{ },
{ uniqueIdentifier: null },
{ uniqueIdentifier: NaN },
{ uniqueIdentifier: 'educba' }
];
let invaliduniqueIdentifierEntries = 0; function isNumber(object) {
return (object !== undefined && typeof(object) === 'number' && !isNaN(object))
}
function filterByuniqueIdentifier(element) {
if (isNumber(element.uniqueIdentifier) && element.uniqueIdentifier !== 0) { return true
}
invaliduniqueIdentifierEntries++ return false;
}
let resultantFilteredArray = sampleArray.filter(filterByuniqueIdentifier); document.getElementById("sampleResult1").innerHTML = 'sampleArray : \n';
for(var counter=0, arrayLen = sampleArray.length; counter<arrayLen; counter++) { var id = sampleArray[counter]['uniqueIdentifier']+",";
var mynode = document.createTextNode(id); document.getElementById("sampleResult1").appendChild(mynode);
}
document.getElementById("sampleResult2").innerHTML = 'Filtered sampleArray : \n' ;
for(var counter2=0, arrayLen2 = resultantFilteredArray.length; counter2<arrayLen2; counter2++) { var id2 = resultantFilteredArray[counter2]['uniqueIdentifier']+",";
var mynode2 = document.createTextNode(id2); document.getElementById("sampleResult2").appendChild(mynode2);
}
document.getElementById("sampleResult3").innerHTML = 'Number Of Invalid Unique Identifier Entries = '+ invaliduniqueIdentifierEntries;
}
</script>
</body>
</html>
Output:
We can use a function or ES2015 Implementation to specify the condition or predicate to be considered while filtering.
Example #3
Let us see an example that implements both these methods. Here, we will filter all the elements containing a specified string of characters.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Demonstration of filter function using function as well as predicate specification method of ES2015.</p>
<button onclick="sampleFunction()">Get Result</button>
<p id="sampleResult1"></p>
<p id="sampleResult2"></p>
<script>
function sampleFunction() {
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday','friday','saturday','educba'] function filterDays1(array, query) {
return array.filter(function(day) {
return day.toLowerCase().indexOf(query.toLowerCase()) !== -1
});
}
var array1=filterDays1(days, 'es'); document.getElementById("sampleResult1").innerHTML = 'Filtered Array : \n';
for(var counter=0, arrayLen = array1.length; counter<arrayLen; counter++) { var id = array1[counter]+",";
var mynode = document.createTextNode(id); document.getElementById("sampleResult1").appendChild(mynode);
}
//ES2015 Implementation
const filterDays2 = (array, query) => {
return array.filter(day => day.toLowerCase().indexOf(query.toLowerCase()) !== -1);
}
var array2=filterDays2(days, 'es');
document.getElementById("sampleResult2").innerHTML = 'Filtered Array Using ES2015 Implementation : \n' ;
for(var counter2=0, arrayLen2 = array2.length; counter2<arrayLen2; counter2++) { var id2 = array2[counter2]+",";
var mynode2 = document.createTextNode(id2); document.getElementById("sampleResult2").appendChild(mynode2);
}
}
</script>
</body>
</html>
The output of the above function is as follows, which is the same for both types of specification of the predicate –
Output:
Recommended Articles
This is a guide to JavaScript Filter Function. Here we discuss the Introduction and Working of the filter() function and different examples and code implementation. You may also look at the following articles to learn more –