JavaScript Filter Arrays with filter

J

The filter method is used to iterate through an array and filter out elements.
filter takes the current value as an argument and apply conditions.

Any array element that returns true will be kept and elements that return false will be filtered out.

The following code filter will array elements that are above 5:

var oldArray = [1,2,3,4,5,6,7,8,9,10];

var newArray = oldArray.filter(function(val){
    if(val > 5)
        return val;
});

console.log(oldArray); // returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(newArray);  // returns [6, 7, 8, 9, 10]

About the author

Imran Pollob

Learn => Practice => Implement => Repeat

Add comment

Categories

Imran Pollob

Learn => Practice => Implement => Repeat

Get in touch