2

Given an array of different elements, arrays and integers, I would like to come up with an array of all the integers contained in the array:

x= [[ 1,2,3], 4, [5,6], 7, 8, [9]]
pretty(x) -> [1,2,3,4,5,6,7,8,9];

I did manage to complete it with a rather ugly reduce, but I'd like to know if there is something prettier to do with it:

x.reduce((t, e) => {
        if (!e instanceof Array) [e];
        return t.concat(e);
    });

Any recommendation?

Thanks!

ggonmar
  • 760
  • 1
  • 7
  • 28

1 Answers1

4

Use .flat:

x= [[ 1,2,3], 4, [5,6], 7, 8, [9]]
x = x.flat(Infinity);
console.log(...x);
x = [[[1, 2, 3]]];
x = x.flat(Infinity);
console.log(...x);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48