JavaScript Array method filter, map

JavaScript Array method filter, map

Array.filter()

The filter() method returns filtered elements in a new array which pass the condition define in callback method

Syntax:


    const newArray = array.filter(function (element, index, array) {
    return condition;
    });


Example: 

   const numbers = [1, 3, 6, 9, 12];

const luckyNumbers = numbers.filter(function(number) {
return number > 7;
});
console.log(luckyNumbers);
// Output: [9, 12]


Array.map()

The map() method creates a new array with the results of calling a function for each element of parent array. This method does not execute for empty element of array.

Syntax:

    const newArray = array.map(function(element, index, arr), thisValue)


Example:        
    // Multiply all the elements of numbers array by 5
const numbers = [1, 2, 3, 4, 5];
const newArray = numbers.map((item) => {
return item * 5;
});
console.log(newArray);
// Output: [5, 10, 15, 20, 25]


Comments

Popular posts from this blog

Top 5 Programming Languages to Learn in 2020

10 NodeJS Tips and Tricks for developers

What is Deno and will it Replace NodeJS?