0

I am trying to count how many time the unique characters appears in a string. but I am stuck at the object iteration where the it only returns 1 no matter how many times same character appears more than one time:

function allUniqueCha(word) {
  var wordObj = {};
  var wordArray = word.split([, ]);
  wordArray.forEach(function(c) {
    wordObj[c] = +1;
  });
  console.log(wordArray);
  console.log(wordObj);
}

allUniqueCha("Bubble")

The output is : {B:1, u:1,b:1,l:1,e:1} but the expected value of key "b" should be 2.

1
  • What is the initial value of wordObj[c]? What happens when you assign +1 to it? Commented Feb 15, 2017 at 23:52

3 Answers 3

4

You wrote:

 wordObj[c]=+1;

With some formatting:

 wordObj[c] = +1;

You always assign +1 to the value, there is no increment here. Try

 wordObj[c] = (wordObj[c] || 0)+1;

And

var wordArray = word.split([, ]);

should be rather

var wordArray = word.split("");

function allUniqueCha(word) {
  var wordObj = {};
  var wordArray = word.split("");
  wordArray.forEach(function(c) {
    wordObj[c] = (wordObj[c] || 0) +1;
  });
  console.log(wordArray);
  console.log(wordObj);
}

allUniqueCha("Bubble")

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

Comments

1

When you do:

wordObj[c] = +1;

you are assigning the value +1 to the property. What you want to do is increment the value by 1, so:

wordObj[c] += 1;

However, initially wordObj[c] doesn't exist so you're trying to increment undefined, which will throw an error. So yo must test if the property exists and if not, create it an initialise it.

function allUniqueCha(word) {
  var wordObj = {};
  var wordArray = word.split([, ]);
  wordArray.forEach(function(c) {
    if (!wordObj.hasOwnProperty(c)){
      wordObj[c] = 0;
    }
    wordObj[c] += 1;
  });
  console.log(wordArray);
  console.log(wordObj);
}

allUniqueCha("Bubble")

You could also use reduce:

function allUniqueCha(word) {
  return word.split('').reduce(function(acc, c) {
    acc[c] = (acc[c] || 0) + 1;
    return acc;
  },{});
}

console.log(allUniqueCha("Bubble"));

Comments

0

This piggy backs on the train of thought in your initial post. Here is one way to solve the problem you are looking for.

function allUniqueCha(word){
  let wordArray = word.split([,]);
  return wordArray.reduce((result, element) => {
    result[element] = result[element] + 1 || 1;
    return result;
  }, {})
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.