Filter()

Advertisement

With the help of filter() array method we’ll filter the and create new array from existing array.

Suppose we have array:

let a = [ 'One', 'Two', 'Three' ];

The array is stored as:

0: "One"
1: "Two"
2: "Three"

Suppose we want to create a new array without the “Two” value.

Then, We’ll use below code:

let b = a.filter( function( item ) {
    if( 'Two' === item ) {
        return false;
    }
    return true;
});

Then, The variable b store the value as:

// Output: ['One', 'Three']

Here, The new array is created with filtered value.

We will do the same with arrow function as:

let b = a.filter( ( item ) => {
    if( 'Two' === item ) {
        return false;
    }
    return true;
});

Or, We’ll use it as:

let b = a.filter( item => 'Two' !== item);

We’ll get the same result.

// Output: ['One', 'Three']

Leave a Reply