简体   繁体   中英

Fastest way to extract two arrays from an object array in javascript

Lets say I have a schema like this:

users: {
   friends: [{name: String, id: String}]
}

what is the fastest way to extract this object array into two separate arrays:

var names = [String]
var ids = [String]

Is there a way to do this without a for loop? This operation needs to be done for a set of users and im trying to avoid nested for loops. Maybe there is a better way to store the friends names and ids?

Use Array.map() :

var names = users.friends.map(function(o) { return o.name; }),
    ids   = users.friends.map(function(o) { return o.id;   });

There's always a loop, somewhere (and I'm not sure what you mean by nested loops?). :)

If you're looking for fastest (which is what you had said), using a map or a forEach isn't generally speaking going to result in faster operation as each iteration is calling a function, which adds overhead.

As you'll see in this jsPerf , it's generally better to use a for-loop construct. First, if the array is long, you'll benefit from only going through the array just once (rather than once for each property). For futher optimization, predeclaring the array size also can improve performance.

var names = new Array(totalFriends),
    ids = new Array(totalFriends), friend;

for (var j = 0; j < totalFriends; j++) {
  friend = friends[j];
  names[j] = friend.name;
  ids[j] = friend.id;
}

A map call is convenient, but likely not the fastest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM