Diego Flores
Diego Flores

Reputation: 123

Javascript map through array to make another array of objects

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)

Upvotes: 0

Views: 354

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370599

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 };
  })
)

Upvotes: 3

Related Questions