-2

I'm trying to remove the indexes of an array in the easiest and most efficient possible way. This is the array like:

Having this array (see snipet):

let arr = [];
arr.push([{id:1}]);
arr.push([{id:2}, {id: 3}]);
arr.push([{id:4}]);
console.log(arr)

the expected result is an array that joins all the objects into one same index.

[
{id: 1},
{id: 2},
{id: 3},
{id: 4}
]

If I iterate every element on the array and add every object to a new array I can get the result I'm expecting but there must be a function or something that simplifies de code..

Thanks in advance

David
  • 614
  • 5
  • 20
  • 1
    `const newArr = arr.map(e => e[0]);` –  Apr 29 '21 at 09:11
  • [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) maybe? –  Apr 29 '21 at 09:12

1 Answers1

1

Yes there is! is the flat() method (see here)

let arr = [
[{id:1}],
[{id:2}],
[{id:3}],
[{id:4}]
];
console.log(arr.flat())

It works also for more annidated sublist, passing a depth parameter.

For those using typescript remember to add es2019 as explained here.

Emanuele
  • 382
  • 3
  • 9
  • It's not working on angular with typescript as it is not recognized in the default compiler, I finally had to use `arr.reduce((acc, val) => acc.concat(val), [])` but still your function is what I was looking for and im going to accept as a valid answer, could you add this code below into the answer for people who is using typescript? thanks! – David Apr 29 '21 at 09:43
  • @David you can use `flat` method also with typescript. See my edit. – Emanuele Apr 29 '21 at 10:22