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?
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
mapor aforEachisn’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.
A map call is convenient, but likely not the fastest.