JS Tutorial

Function Reference

Method Reference

  • JS String
  • JS Array
  • JavaScript Array filter() Method

    The filter() method creates a new array with all elements those are passed condition by the provided function.

    Note:The filter() method does not change the original array.

    array.filter(callback, thisValue);
    OR
    array.filter(function(currentElement, currentIndex, array), thisValue)
    

    Parameters

    Parameter Description
    function(currentElement, currentIndex, array)
    currentElement Required. The value of the current element being processed.
    index Optional. The array index of the current element.
    array Optional. The array filter() was called upon, current elements belongs to.
    thisValue Optional. : value passed to the function used as "this", this parameter is blank then default value is "undefined" .

    Details

    Return : A new array return that passed the function conditions. If no elements pass the test, an empty array will be returned.
    Version : ECMAScript 5 (ES5)

    Examples -

    Get the elements greater than 5 value

    var numbersArary = [2,5,6,7,8,10];
    var newResultValue = numbersArary.filter(testFunc)
    
    function testFunc(number) {
      return number>5
    }
    console.log(newResultValue);
    //Output : [6, 7, 8, 10]
    

    Return an array of all the values in the persons ages is greater than 18

    const persons = [
      { id: 10, name: 'Vishal Gupta', age:15},
      { id: 11, name: 'Harsendra Singh', age:25},
      { id: 12, name: 'Vipin Katiyar', age:38},
      { id: 13, name: 'Umesh Yadav', age:40}
    ];
    let adultAges = persons.filter(function (person) {
        return person.age>180
    });
    console.log(adultAges);
    
    //Output:
    0: {id: 11, name: "Harsendra Singh", age: 25}
    1: {id: 12, name: "Vipin Katiyar", age: 38}
    2: {id: 13, name: "Umesh Yadav", age: 40}