Skip to content

Array.map.filter

Posted on:February 11, 2023 at 05:00 AM

Arrays are one of the important property in all languages. We are going to see how easily we can manipulate or sort using map and filter methods.

Map

It returns the array with exact length we provide after manipulation.

const arr1 = [2, 4, 6, 8, 10];
const arr2 = arr1.map(Math.sqrt);

console.log(arr2);
// [1.414, 2, 2.449, 2.828, 3.162]
function multiplyBy5(value) {
    return value * 5;
}

const arr1 = [2, 4, 6, 8, 10];
const arr2 = arr1.map(multiplyBy5);

console.log(arr2);
// [10, 20, 30, 40, 50];

Filter

It returns the array with the matched elements.

function oddNumber(value) {
    return value % 2 != 0;
}

const arr1 = [2, 3, 4, 5, 6, 7];
const arr2 = arr1.filter(oddNumber);

console.log(arr2);
// [3, 5, 7]

Note: You can use map and filter together too - [1, 2, 3].map(fn1).filter(fn2)

sayanora