Search code examples
javascriptsetincrement

incrementing a set if existing


I have a string "abacabad" being passed in to my function as s

What I want to do:

  • create a new set
  • go through each letter from the string. if the letter exists I increment it by 1
  • if it doesn't exist we create the set by initializing it as 1

What my code is logging:

Set(0) { a: 1, b: 1, c: 1, d: 1 }

what it should be logging:

Set(0) { a: 4, b: 2, c: 1, d: 1 }


function solution(s) {
  arr = new Set()
  for (e of s) {
    if (e in arr) {
      arr[e]++;
    }
    if (arr.has(e) == false) {
      arr[e] = 1;
    }
  }
  console.log(arr)
}

solution('abacabad');


Solution

  • A Set is a collection of unique elements. It's not a Map (key/value) store.

    There's tons of issues in that code so I won't enumerate them all, but you simply aren't using the right kind of object and then are mixing APIs, notably defining keys of objects mixed with the actual Set's API.

    function solution(s) {
      const countByChar = new Map();
      for (char of s) {
        const count = countByChar.get(char) || 0;
        countByChar.set(char, count + 1);
      }
      return countByChar;
    }
    
    const countByChar = solution('abacabad');
    
    console.log(Array.from(countByChar.entries()));