简体   繁体   中英

Javascript: Array of objects to object containing arrays of values - most performant way?

Desired: loop over a single array of objects, and construct multiple arrays for assigning to an object, based on the keys in those objects in most concise and performant manner. Two approaches:

One:

const arrayOfObjectsToObjectOfArraysOfValues = items => {
  const newArrayOne = []
  const newArrayTwo = []
  const newArrayThree = []

  items.forEach(({ value1, value2, value3 }) => {
    newArrayOne.push(value1)
    newArrayTwo.push(value2)
    newArrayThree.push(value3)
  })

  return { newArrayOne, newArrayTwo, newArrayThree }
}

Two:

const arrayOfObjectsToObjectOfArraysOfValues = items => ({
   newArrayOne: items.map(({ value1 }) => value1),
   newArrayTwo: items.map(({ value2 }) => value2),
   newArrayThree: items.map(({ value3 }) => value3),
})

Edit (There is also this option):

const arrayOfObjectsToObjectOfArraysOfValues = items => {
  return items.reduce((r, { value1, value2, value3 }, i) => {
    r.newArrayOne[i] = value1;
    r.newArrayTwo[i] = value2;
    r.newArrayThree[i] = value3;
    return r;
  }, { newArrayOne: [], newArrayTwo: [], newArrayThree: [] });
}

Obviously the second one is more concise, but it can be criticized for doing three loops where only one is required. On the other hand the first one is doing 3 operations per loop cycle. The key question option is "which (or is there another more elegant) option (which) is most performant?"

Ok, I got on the jsperf bandwagon for my first time... looks like the answer here is it depends on the client:

https://jsperf.com/arrayofobjectstoobjectofarraysofvalues/1

On Firefox option 1 is 23% slower. (832,000 ops per second baseline)
On Chrome option 2 is 88% slower. (248,000 ops per second baseline)
On Safari option 2 is 48% slower. (158,000 ops per second baseline)

Edit: reduce option is 2% slower in Chrome & Safari, but 50% slower in Firefox.

So, probably yes, option 1 is better in most cases. A pity for conciseness... Also, go Firefox - so fast!

Finally, I suppose Option one can become a little conciser using reduce.

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