develop05
develop05

Reputation: 485

merging mutiple arrays inside one array

So, I have an array full of full of arrays of one object

[[{id: 0, name: example1}], [{id: 1, name: example2}], [{id: 2, name: example3}]]

What I'm trying to do is to merge all of these array and make them look like this

[{id: 0, name: example1}, {id: 1, name: example2}, {id: 2, name: example3}]

I tried using concat but it still not working

let a=arr[0], b=arr[1], c=arr[2]
let d = a.concat(b,c)
console.log(d)

the arrays are still there

Upvotes: 0

Views: 57

Answers (4)

Ori Drori
Ori Drori

Reputation: 191936

Your code will flatten the three arrays, as you can see here:

const arr = [[{id: 0, name: 'example1'}], [{id: 1, name: 'example2'}], [{id: 2, name: 'example3'}]]

let a=arr[0], b=arr[1], c=arr[2]

let d = a.concat(b,c)
console.log(d)

However, it's not scalable. If the array contains 6 items, you'll need to create 3 variables more, etc...

Another way to flatten the sub-arrays is by spreading the array into Array.concat():

const arr = [[{id: 0, name: 'example1'}], [{id: 1, name: 'example2'}], [{id: 2, name: 'example3'}]];

const result = [].concat(...arr);

console.log(result);

Upvotes: 5

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

let input = [[{id: 0, name: 'example1'}], [{id: 1, name: 'example2'}], [{id: 2, name: 'example3'}]]

output = input.map(([firstElementOfArray]) => firstElementOfArray)

console.log(output)

Upvotes: 0

samhain1138
samhain1138

Reputation: 1035

You have an array of arrays.

let a=arr[0][0], b=arr[1][0], c=arr[2][0]
let d = [a, b, c]
console.log(d)

Upvotes: 0

user5047085
user5047085

Reputation:

flattening the array is the right way to go, pass the array to this:

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}

You can use lodash for this also: https://www.npmjs.com/package/lodash.flattendeep

Upvotes: 2

Related Questions