2

If I had an array of letters how would I go about turning each letter into an object key with a value of how many there are in that array in JavaScript?

For example:

const array = ['a', 'b', 'c', 'c', 'd', 'a'];
const obj = { a: 2, b: 1, c: 2, d: 1};
  • 4
    Looks like a cool little puzzle. Have you tried to solve it yourself? Would you mind sharing what you did with us? – Mike Cluck Oct 31 '18 at 20:12

2 Answers2

1

Objects can be indexed very similarly to arrays in JavaScript, like so:

const obj = {};
array.forEach((element) => {
  //Check if that field exists on the object to avoid null pointer
  if (!obj[element]) {
    obj[element] = 1;
  } else {
    obj[element]++;
  }
}
Amethystx87
  • 488
  • 3
  • 6
1

you can simply use Array.reduce() to create a frequency map :

const array = ['a', 'b', 'c', 'c', 'd', 'a'];
let result = array.reduce((a, curr) => {
  a[curr] = (a[curr] || 0)+1;
  return a;
},{});
console.log(result);
amrender singh
  • 7,949
  • 3
  • 22
  • 28