JavaScript Array filter Method

JavaScript Array filter Method

javascript array filter method; In this tutorial, you will learn JavaScript Array filter() method. And how to filter js arrays element and as well as filter array of objects.

JavaScript array filter()

In a javascript programming language, It’s a common thing to create a new array and manipulate array elements using the javascript built-in array methods like, array push(), array pop() , array shift() and array unshift, etc.

Assume you have an array of lang objects in javascript, and where each object has two properties: name and student and lang means languages, see the following example:

let lang = [
    {name: 'php', student: 100},
    {name: 'java', student: 500},
    {name: 'c', student: 50},
    {name: 'python', student: 200},
    {name: 'javascript', student: 1000}
];

And you want to search the in this array objects, whose students are greater than 100. So typically you need to use for loop and test if the value of the student the property satisfies the condition, like following:

let pLang = [];
let lang = [
    {name: 'php', student: 100},
    {name: 'java', student: 500},
    {name: 'c', student: 50},
    {name: 'python', student: 200},
    {name: 'javascript', student: 1000}
];
for (let i = 0; i < lang.length; i++) {
    if (lang[i].student> 100) {
        pLang.push(lang[i]);
    }
}
console.log(pLang);

Output:

[
  0: {name: "java", student: 500}
  1: {name: "python", student: 200}
  2: {name: "javascript", student: 1000}
]

You have seen the example given how much code has to be written to find an element an array object in javascript.

If you will use JavaScript Array filter() method that allows you to do this same task in a more concise and more reliable way.

See the following example returns the same result as the example above:

let lang = [
    {name: 'php', student: 100},
    {name: 'java', student: 500},
    {name: 'c', student: 50},
    {name: 'python', student: 200},
    {name: 'javascript', student: 1000}
];
let pLang = lang.filter(function (e) {
    return e.student > 100;
});
console.log(pLang);

In this example, use js array filter() method of the lang array object and passed into a function that which is tested each element of lang array object.

Inside the function, use js if statement to check the student of each lang array element is greater than 100.

In this example, the function returns trueand false based on specified test conditions. The filter() method includes only the element in the result array if the element satisfies the test in the function that we pass into.

Output:

[
  0: {name: "java", student: 500}
  1: {name: "python", student: 200}
  2: {name: "javascript", student: 1000}
]

In javascript ES6 arrow function is more concise and more reliable way. Use the arrow function (=>) instead of regular function.

See the following example:

let lang = [
    {name: 'php', student: 100},
    {name: 'java', student: 500},
    {name: 'c', student: 50},
    {name: 'python', student: 200},
    {name: 'javascript', student: 1000}
];
let pLang = lang.filter(e=> e.student> 100);
console.log(pLang);

Syntax of JavaScript Array filter() method

The following illustrates the syntax of the js filter() method:

arrayObject.filter(callback, contextObject);

This method accepts parameters: a callback function and an optional object.

Within, the filter() method iterates over each element of the array and passes each element to the callback function . If the callback function is true, it contains the element in the return array.

JavaScript also has many iterative methods apart from the Array filter() method. Which is work with JavaScript’s Array. Such as every(), some(), map() and forEach(), the callback function

function callback(currentElement, index, array){
   // ...
}

The js callback function accepts 3 parameters:

  • This currentElement parameter of an array is that, the current element, which processed by the callback function.
  • The index is second parameter of an array is the current iteration index of an array element.
  • The array is the array object being traversed.

Remember Some Points:

  • Note that,index and array both arguments are optional.
  • Note that second point, the filter() method does not change the original array.

Example: Array filter() method

Find the language, whose greater than 100 students from an array of object using filter() , sort() and map() method. Because it returns a new array.

See the following example:

let lang = [
    {name: 'php', student: 100},
    {name: 'java', student: 500},
    {name: 'c', student: 50},
    {name: 'python', student: 200},
    {name: 'javascript', student: 1000}
];
lang
     .filter(lang => lang.student > 100)
     .sort((c1, c2) => c1.student - c2.student)
     .map(lang => console.log(lang.name + ':' + lang.student));

Output:

python:200
VM61:13 java:500
VM61:13 javascript:1000

How it works.

  • First of all, the filter() method returns the lang whose student are greater than 100.
  • Second, the sort() method sorts the resulting language by the student in descending order.
  • Finally, the map() method shows each element.

Suppose, you have a numeric array in javascript and you want to find even numbers in it using the array filter().

See the following example:

let num = [1, 2, 3, 4, 5, 6, 10, 12, 16, 20, 22];
let result = num.filter(function(num){
    return num % 2 === 0;
});
console.log(result); // [2, 4, 6, 10, 12, 16, 20, 22]

In javascript, An array of objects can also be filtered very easily with the javascript array.filter(). The following example represents how:

var fruits = [
  {name: "Mango", count: 20},
  {name: "Orange", count: 12},
  {name: "Banana", count: 32},
  {name: "Apple", count: 56},
];
 
var availableFruits = fruits.filter(function(fruit) {
  return fruit.count >20;
});
// Output: [{name: "Banana", count: 32},{name: "Apple", count: 56}]

In javascript, filter array of objects with multiple conditions, it is very easily with the javascript array.filter(). The following example represents how:

var fruits = [
  {name: "Mango", count: 20,quality:"good"},
  {name: "Orange", count: 12,quality:"average"},
  {name: "Banana", count: 32,quality:"bad"},
  {name: "Apple", count: 56, quality:"good"},
];
 
var availableFruits = fruits.filter(function(fruit) {
  return fruit.count >20 && fruit.quality==='good';
});
// Output: [{name: "Apple", count: 56, quality: "good"}]

Conclusion

In this tutorial, you have learned how to use the JavaScript Array filter() method to filter elements in an array-based specified test condition.

Recommended JavaScript Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *