3

Here is what I tried:

let a = [[1,2], [3,4]];

a.map(val => ...val)
// => SyntaxError: expected expression, got '...'
// Expected output: [1,2,3,4]

I tried with explicit return statement and surrounding value with parenthesis but none worked...

I just wonder if there is a simple way to return "spreaded array" ?

Edit: Now I have seen this SO question which has got precision on how spread operator works although in doesn't really answer the question on how to "flatten" an array (I modified the title of the question).

TOPKAT
  • 6,667
  • 2
  • 44
  • 72
  • 5
    Spreading creates multiple values – a function in JavaScript can only return one value – Patrick Hund Feb 18 '19 at 11:26
  • 1
    You should see `Array.prototype.flat()`. – samb102 Feb 18 '19 at 11:27
  • 2
    You can do `[].concat(...a)` – HMR Feb 18 '19 at 11:27
  • 1
    @PatrickHund No, spreading doesn't "create" any values, it's not an expression on its own. Spread syntax is part of only array literal and function call syntax where it has a specific meaning, and the three dots are simply *syntactically* invalid elsewhere. – Bergi Feb 18 '19 at 11:38
  • Maybe I expressed my comment incorrectly. I know what spread syntax is and how it works. Never mind. – Patrick Hund Feb 18 '19 at 11:41

3 Answers3

7

This isn't valid syntax, for this to work you need to spread ("unpack" the contents of) your array into a container of some sort (such as an array). However, if you were to do something like:

a.map(val => [...val])

you would not be doing much with your array, and instead, you would end up with copies of the same array. Thus, you can use different methods other than .map such as .reduce or .flatMap/.flat to achieve your desired output:

Using .reduce with the spread syntax:

let a = [[1,2], [3,4]];

let res = a.reduce((acc, val) => [...acc, ...val], []);
console.log(res)

Using .flatMap():

let a = [[1,2], [3,4]];

let res = a.flatMap(val => val); // map the contents (without the holding array) [[1, 2], [3, 4]] -> [1, 2, [3, 4]] -> [1, 2, 3, 4]
console.log(res)

.flatMap() is, however, useless here, and thus using .flat() would simply suffice:

let a = [[1,2], [3,4]];

let res = a.flat();
console.log(res)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
4

Try to use a.flatMap(x=>x); to flat array and map elements or flat (with no mapping)

a.flat();

let a = [[1,2], [3,4]];

let r=a.flat();

console.log(r);

In flat arg you can set deep-level of flatting - setting Infinity will flat any nested array

let a = [[1,2,[3,4,[5,[6]]]], [[7,[8]],9]];

let r=a.flat(Infinity);

console.log(r);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2

As written in comments, functions can only return one value.

But there is a simple trick what you can use:

let a = [[1,2], [3,4]];

a.reduce((a,b) => a.concat(b),[])
// Expected output: [1,2,3,4]
FZs
  • 16,581
  • 13
  • 41
  • 50