0

I want to go through an array of strings, and depending on what the string is, make an array of objects.

For example, if the array is:

[a,a,a,b,b,c,d]

I want to map through the array and make an object with key and value pairs that add up the strings consecutively:

[{a:1},{a:2},{a:3},{b:1},{b:2},{c:1},{d:1}]

How do I do this?

I've tried mapping through, but I can't get how to add on to the previous object's value (a:1 -> a:2)

1 Answer 1

3

While mapping, you need to store a separate count of how many times each item has appeared, and increment the appropriate key each iteration. You might use a Map for this:

const input = ['a','a','a','b','b','c','d'];
const map = new Map();
console.log(
  input.map(char => {
    const count = (map.get(char) || 0) + 1;
    map.set(char, count);
    return { [char]: count };
  })
)

Sign up to request clarification or add additional context in comments.

6 Comments

ahh, that makes sense. Thanks!!
anyway can you help me understand how the map.get(char || 0) works?
@DiegoFlores note the position of the closing parens - it's map.get(char) || 0, which means get either the defined value for that char, or if the value was undefined (or othereise "falsey") replace it with a real zero, so that the subsequent + 1 will work. undefined + 1 isn't legal.
@DiegoFlores The map starts out empty. The first time a key is encountered (like the a on the first iteration), map.get(char) will return undefined, which isn't a number that can be added to. So, map.get(char) || 0 is a quick way of getting an expression that evaluates to 0 if the key does not exist in the map yet. If the key does exist in the map already, then the expression evalutes to that (numeric) count.
ahh, I see! and then map.set updates the key/value pair of map, which can then be used for the next char in the array?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.