0

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

1

4 Answers 4

5

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);

Sign up to request clarification or add additional context in comments.

1 Comment

That's a better idea.
2

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

Comments

0

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)

2 Comments

@zerkms it would have made it easier if you supplied a working piece of code yourself, to be honest, e.g., the initial arrays. It's hard to work with pseudo-code ;-)
It's not me who asked the question.
0

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

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

console.log(output)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.