1

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.

Ievgen S.
  • 191
  • 2
  • 6
  • Why do you *want* to write this using `reduce`? Since you want to create an array of results, `filter` and `map` are totally appropriate. – Bergi Oct 07 '18 at 20:21
  • yes, both filter)_ and map() are appropriate. But, using reduce() -- I proved already -- a script uses 10 steps less. With filter() and map() I should go through an array twice. Reduce() allow me only once. – Ievgen S. Oct 07 '18 at 20:29

2 Answers2

3

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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]
kyle
  • 691
  • 1
  • 7
  • 17