serg serg - 3 months ago 8
Javascript Question

How to create a function that when placed as an array element would produce multiple array elements?

Is it possible to create a function

magic()
that would turn this:

[{a:1}, {b:2}, magic(), {e:5}]


into:

[{a:1}, {b:2}, {c:3}, {d:4}, {e:5}]

Answer

Not with that precise syntax, no. You can get really close in ES2015, but not exactly identical (in ES5 and earlier, you can't really get close).

In ES2015 ("ES6") and later, you can make magic return any iterable (like an array), and use it with spread notation:

let a = [{a:1}, {b:2}, ...magic(), {e:5}];
// Spread notation ----^^^

Example:

// REQUIRES ES2015+ SUPPORT
function magic() {
  return [{c: 3}, {d: 4}];
}
let array = [{a:1}, {b:2}, ...magic(), {e:5}];
console.log(array);

In ES5 and earlier, you can make magic return an array and use concat:

var array = [{a:1}, {b:2}].concat(magic()).concat([{e:5}]);

Example:

function magic() {
  return [{c: 3}, {d: 4}];
}
var array = [{a:1}, {b:2}].concat(magic()).concat([{e:5}]);
console.log(array);

That's not hyper-efficient as it creates and throws away a couple of temporary arrays, but 99.99% of the time, you don't care.