Hacker News new | ask | show | jobs
by ReleaseCandidat 1631 days ago
Ah, sorry, so you have to concat the arrays using `concat`.

    [1, 2, 3, 4, 5].reduce((acc, n) => n % 2 === 1 ? acc.concat([2*n]) : acc, [])
2 comments

Wouldn't recommend doing this - if the original array is of significant length this'll get quite slow because `acc.concat` has to create a brand new array of slightly longer length on each iteration it's called. Better to just use `push` like you suggested before and then return the array if you want to use `reduce`.
Yes, of course, that's why I used `push` at first.
Use the comma operator: (acc.push(2*n), acc) will return acc. Or e.g.

  [1, 2, 3, 4, 5].reduce((acc, n) => (n % 2 ? acc.push(2*n) : null, acc), [])
If you're just iterating through the array and mutating an object on each iteration, just use a for loop.
Obviously you can alternately write:

  let input = [1, 2, 3, 4, 5], output = [];
  for (let i = 0; i < input.length; ++i) {
    let n = input[i];
    if (n % 2) output.push(2*n);
  }
  return output;
But in some circumstances the other style can be more convenient / legible. The immediate question was about pushing to an array and then returning the array, for which the comma operator can be handy.
No argument that the comma operator is a neat trick when you need it.

FWIW, it's 2022:

  const output = [];
  for (const n of [1, 2, 3, 4, 5]) {
    if (n % 2) output.push(2 * n);
  }
Surely the spread operator is nicer here?

    [1, 2, 3, 4, 5].reduce((acc, n) => n % 2 === 1 ? [ ...acc, 2 * n ] : acc, [])
This is not efficient. Each iteration creates a new array instance due to the spread operator.
`acc.concat()` also creates a new array instance, so I don't get your point.