JavaScript Array filter Method Filtering Arrays
Today, We want to share with you JavaScript Array filter Method Filtering Arrays.
In this post we will show you JavaScript Array filter Method Filtering Arrays, hear for Filtering Arrays with Array using javascript we will give you demo and example for implement.
In this post, we will learn about JavaScript Array filter() Method with an example.
The JavaScript simple Array filter to method creates a new simple array by filtering used function out the elements of an existing Like as an array using a callback function.
The JavaScript simple Array filter method and its iterates over the each value of an simple array passing it to a callback function.
Syntax : filter() function
var filteredArray = array.filter(callback [, contextObject])
List of Parameters
callback
The callback function to use in javascript
contextObject
simple Object to be used as a all context for the callback function in javascript
filter() function Return Value
It’s Returns created an array.
Example of JavaScript Array filter
var nameList = [ {name:'segment A', project:20, kpi:'Kpi 1'}, {name:'segment B', project:60, kpi:'Kpi 2'}, {name:'segment C', project:22, kpi:'Kpi 3'}, {name:'segment D', project:40, kpi:'Kpi 4'} ]; var arrayfiltervalu = nameList.filter(function (product) { return product.name == "segment B" && product.project < 30; }); //To See Output all Result as Array alert(JSON.stringify(arrayfiltervalu));
filter() Array Method in JavaScript
var srnumber = [1, 3, 6, 8, 11]; var drdatano = srnumber.filter(function(number) { return number > 7; });
Output// [ 8, 11 ]
Filtering an array of objects
var subject = [ {name: “Angulajs”, franchise: “ng”}, {name: “Laravel”, franchise: “lv”}, {name: “vuejs”, franchise: “lv”}, {name: “magento”, franchise: “mg”} ]; var laraveldis = subject.filter(function(item) { return item.franchise == “lv”; });
output
// [ {name: “Laravel”, franchise: “lv”}, {name: “vuejs”, franchise: “lv”} ]
Example is really simple : using filter() function
var aarrayname = [5, 4, 3, 2, 1]; smallvalues = aarrayname.filter(function(x) { return x < 3 }); // output [2, 1] everyother = aarrayname.filter(function(x,i) { return i%2==0 }); // output [5, 3, 1]