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};
1
  • 4
    Looks like a cool little puzzle. Have you tried to solve it yourself? Would you mind sharing what you did with us? Commented Oct 31, 2018 at 20:12

2 Answers 2

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]++;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.