Ievgen S.
Ievgen S.

Reputation: 191

abc.filter().map() ==> to reduce() How should I use it? JavaScript

there is an array:

let x = [12,2,3.5,4,-29];
let squared = x.filter((a) => a>0 && Number.isInteger(a)).map((a) => a**2);

please, how to write this using reduce()? The point is -- get squared numbers in given array (only integers), greater than '0'. Any ideas? Thanks.

Upvotes: 1

Views: 156

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386550

You could use a conditional (ternary) operator ?: and take either the squared value or an empty array for concatination to the accumulator.

var x = [12, 2, 3.5, 4, -29],
    squared = x.reduce((r, a) => r.concat(a > 0 && Number.isInteger(a)
        ? a ** 2
        : []
    ), []);

console.log(squared);

Or, as Bergi suggest, with a spreading of the values.

var x = [12, 2, 3.5, 4, -29],
    squared = x.reduce((r, a) => a > 0 && Number.isInteger(a) ? [...r, a ** 2] : r , []);

console.log(squared);

Upvotes: 3

kyle
kyle

Reputation: 691

Original:

let x = [12,2,3.5,4,-29];
let squared = x.filter((a) => a>0 && Number.isInteger(a)).map((a) => a**2);

Now, think about what we want to do here in order to use the reduce method.

We want take an array and return a new array composed of the squares of all positive integers in our original array.

This means our accumulator in reduce should be an array, since we're returning an array at the end. It also means that we need to include the logical control flow to only add elements to our accumulator that are positive integers.

See below for an example:

const x = [12,2,3.5,4,-29];
const squared = x.reduce((acc, val) => val > 0 && val % 1 === 0 ? acc.concat(val ** 2) : acc, []);

console.log(squared);
// [144, 4, 16]

Upvotes: 1

Related Questions