Introduction
The filter()
Array method creates a new array with elements that fall under a given criteria from an existing array:
var numbersArr = [3, 5, 7, 9, 10, 11, 15]; var aboveSeven = numbersArr.filter(function(number,index) { return number > 5; }); Output: [ 9, 10, 11, 15]
filter() does not execute the function for array elements without values
and does not change the original array.
Syntax:
index: Optional. The array index of the current element
arr: Optional. The array object the current element belongs to
thisValue: Optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value
array.filter(function(currentValue, index, arr), thisValue)currentValue: Required. The value of the current element
index: Optional. The array index of the current element
arr: Optional. The array object the current element belongs to
thisValue: Optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value
Let's take another example, to find the mobiles which price is greater than 15000
const mobiles = [ {'brand':'Realme','model':'m6','price':1500}, {'brand':'Redmi','model':'m7','price':10000}, {'brand':'karbon','model':'m8','price':4852}, {'brand':'micromax','model':'m9','price':18000}, {'brand':'oneplus','model':'m10','price':45000}, {'brand':'poco','model':'m11','price':20000}, {'brand':'oneplus','model':'m12','price':10600}, ]; const highEndMobiles = mobiles.filter( m => m.price > 15000); Output: [ {'brand':'micromax','model':'m9','price':18000}, {'brand':'oneplus','model':'m10','price':45000}, {'brand':'poco','model':'m11','price':20000} ]
0 Comments