Search This Blog

2026/08/10

Javascript:filter array for even square

 



filter an array which are even

Code:
let arr = [2, 3, 4, 5, 6, 7];

let result = arr.flatMap((item) => {
    if (item % 2 === 0) {
        return [item * item];
    }
    return [];
});

console.log(result);

Output:
[4, 16, 36]

Explanation:
  flatMap is combination of filter & map.If no value is to be
returned is empty array & return value shoulld be put i array syntax.

No comments:

Post a Comment