2

Why chaining function on array.flat not working as expected

const input = [[[{"type":"banana"},{"type":"orange"}]]];

console.log(input.flat(2).push({"type":"grapes"}));

What I expect is, it should remove the 2 array wrapper and push a new item to input

But I get only the length why is that ?

user007
  • 189
  • 2
  • 13

4 Answers4

3

Array#push returns the new length of the array.

You could concat the array (Array#concat) with a new element and get the new array.

console.log(input.flat(2).concat({ type: "grapes" }));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • What If I need to add the grapes as first item? how does unshift works with concat ? – user007 May 24 '19 at 06:25
  • `unshift` returns the new length, as `push`, because it's the other side of the same action. but you could switch the flat part and the concat: `[{ type: "grapes" }].concat(input.flat(2))` – Nina Scholz May 24 '19 at 06:27
  • hi @Nina Scholz could you please try to answer this question https://stackoverflow.com/questions/56334074/creating-new-data-object-set-from-multiple-nested-arrays – user007 May 28 '19 at 03:27
1

Array.push mutates the array itself and returns only the length of the array. You can log the array in the next line after the push statement.

0

The push method returns the new length of the array and mutates it.

Try instead:

const input = [[[{"type":"banana"},{"type":"orange"}]]];
const flattened = input.flat(2)
flattened.push({"type":"grapes"});
console.log(flattened) 
/* 
  [
    {type:"banana"},
    {type:"orange"},
    {type:"grapes"}
  ] 
*/
FZs
  • 16,581
  • 13
  • 41
  • 50
  • 1
    `flat()` does not mutate the original array. So you have to store the returned array in another variable before using `push()` or you will lost it. I believe you wanted to write: `let flattenArr = input.flat(2); flattenArr.push(...); console.log(flattenArr);` – Shidersz May 23 '19 at 19:48
  • @Shidersz Thanks, I haven't noticed this, and I've corrected it now :D – FZs May 23 '19 at 19:52
0

You can also other than Array.concat also spread into a new array to achieve the same result:

const input = [[[{"type":"banana"},{"type":"orange"}]]];

console.log([...input.flat(2), {"type":"grapes"}]);

The issue in your code however is that Array.flat returns a whole new array for you to work with and Array.push simply returns the new length of the array (so you need to keep a reference to the array). So with some refactoring:

const input = [[[{"type":"banana"},{"type":"orange"}]]];

let newArr = input.flat(2)  // <-- this would return a new array

newArr.push({"type":"grapes"})  // We do not care what push returns since we have a reference to the array

console.log(newArr)

You get the expected result

Also note of caution with Array.flatMap and Array.flat ... both do not have support in IE and you would need a polyfill

Akrion
  • 18,117
  • 1
  • 34
  • 54