4

I have a object where data is an array of objects, inside data object I have one users property which is an array.

I need to get all the users into a single array. I have written using map and concat.

Is there any way I can have a better solution, or this is correct?

See the below snippet.

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}

var users = response.data.map(o => o.users)

const usersCollection = [].concat(...users)

console.log(usersCollection)

5 Answers 5

17

You can use Array.prototype.flat():

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth | Optional

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}

var users = response.data.map(o => o.users).flat();

console.log(users);

You can also try with Array.prototype.flatMap() which is identical to a map followed by a call to flat of depth 1.

var users = response.data.flatMap(o => o.users);
Sign up to request clarification or add additional context in comments.

1 Comment

is this flat method is supported in nodejs version more than 10 ?
0

If Using ES6, utilizing the power of spread with Array.reduce

var response = {
  data: [{
    users: [1, 2, 3]
  }, {
    users: [4, 5, 6]
  }]
}

var users = response.data.reduce((accumulator, obj) => [...accumulator, ...obj.users], []);

console.log(users);

Comments

0

Using ES6 Spread operator you can do the job quick.

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}

let wantedArray = [];
for(let v of response.data){
  wantedArray.push(...v.users);
}

console.clear();
console.log(wantedArray);

Comments

0

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flat of depth 1, but flatMap is often quite useful, as merging both into one method is slightly more efficient

response.data.flatMap(({users})=>users)

You should be careful with vendor support though if you’re running in the browser.

Comments

0

You can use ES6 spread operator

var response = {data: [{users: [1,2,3]}, {users: [4,5,6]}]}    
var NEWARRAY = [];
for(var v of response.data){
  NEWARRAY.push(...v.users);
}
console.log(NEWARRAY);

2 Comments

Please don’t post duplicate answers. This exact solution has already been provided.
FYI - The vast majority of authoritative bodies in the JS community recommend naming conventions where uppercase variables are used specifically for defining constants... Google, Mozilla, Airbnb, W3.

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.