0

Whats the most elegant way of mapping a list into a list of dictionaries n at a time using react?

["a", "b", "c"] => [{0:"a", 1:"b"}, {0:"c"}]
Ajax
  • 1,418
  • 2
  • 17
  • 38
  • What do you mean _"using react"_? This seems to be a basic JS task, iterating in groups of a given length, in which case see https://stackoverflow.com/q/28359919/3001761. Also note in JS nomenclature those are _objects_, not _dictionaries_, and _arrays_, not _lists_. – jonrsharpe Mar 23 '22 at 17:40
  • What is the algorithm behind your example? – Nachtgold Mar 24 '22 at 08:03
  • Literally splitting a list into groups of n, where each item corresponds to a unique dictionary key. – Ajax Mar 25 '22 at 18:30

1 Answers1

0

You can use reduce for this:

['a', 'b', 'c'].reduce((acc, currentValue, currentIndex) => {
  acc.push({ [currentIndex]: currentValue });

  return acc;
}, []);

Here's a great Twitter post that explains how various array methods work:

https://twitter.com/steveluscher/status/741089564329054208