2

Trying to Map an Array, which one of these implementations is better performance-wise? Is there a better solution?

//Given the following Array of people:
const people = [ { name: 'Alice', available: true },  { name: 'Bob', available: false }, { name: 'Charlie', available: true }];

const mapWithReduce = (people) => people.reduce((map, person) => ({ [person.name]: person.available, ...map }), {});

const mapWithForEach = (people) => {
    const map = {};
    people.forEach((person) => map[person.name] = person.available);
    return map;
}

I find mapWithReduce prettier but I don't know if ...map} is copying the map every iteration. mapWithForEach seems more performant.

J. Nicastro
  • 254
  • 3
  • 11

3 Answers3

2

I like this solution.

const people = [ 
  { name: 'Alice', available: true },
  { name: 'Bob', available: false },
  { name: 'Charlie', available: true }
];

const peopleMap = people.reduce((map, person) => {
  map[person.name] = person;
  return map;
}, {});

console.log(peopleMap);

Looks equals than the forEach solution but without creating local vars.

https://jsperf.com/arraymapeachreduce/9

enter image description here enter image description here

Eugenio Valeiras
  • 980
  • 1
  • 9
  • 30
  • Good improvement. I would suggest using [this test](https://jsperf.com/arraymapeachreduce/10) though, as declaring the array of `people` should not be considered within the benchmark. All that does is add a constant offset to ops/sec for each case. – Patrick Roberts Jan 22 '19 at 14:46
2

Performance-wise, using a for loop is the fastest.

benchmark

const people = [{ name: 'Alice', available: true }, { name: 'Bob', available: false }, { name: 'Charlie', available: true }]

const mapWithForLoop = (key, value) => array => {
  const map = {}

  for (let i = 0; i < array.length; i++) {
    const entry = array[i]
    map[entry[key]] = entry[value]
  }

  return map
}

const mapPeopleWithForLoop = mapWithForLoop('name', 'available')

console.log(mapPeopleWithForLoop(people))

The forEach() method comes close, though.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
1

they should both be identical if you make their implementations the same and reduce is a little easier to grok because developers know that it has an accumulator whereas in the forEach, you're just sort of implementing reduce yourself

const mapWithReduce = (people) => people.reduce((map, person) => 
  {
    map[person.name]: = person.available;
    return map
  }, {}
);

edit: it's possible that under the hood forEach is more performant, but if you're using babel or another transpiler, it's probably a moot point because at this point, they should do the work of making the more idiomatic version performant. (source)

wmp224
  • 447
  • 3
  • 11