Skip to content
Advertisement

I want to make a this count object but i dont know how to solve it

function test1(str) {
  let arr = str.toLowerCase().split(" ");
  let obj = {};
  let len = arr.length;
     
  for (let i = 0; i < len; i++) {
    if (obj[arr[i]]) {
      obj[arr[i]] ++
    } else if(obj[arr[i]] === " ") {
      obj[arr[i]] = 0;
    } else {
      obj[arr[i]] = 1;
    }
  }
      return obj;
}

let output = obectCount('ask a bunch try a BUNCH get a bunch');
console.log(output); // --> { ask: 1, a: 3, bunch: 3, try: 1, get: 1 };

I expect it to be { ask: 1, a: 3, bunch: 3, try: 1, get: 1 }; but it is wrong in various cases – how can I fix it?

Thank you for your interest. But there was a problem with the other conditions. its other condition , just updated..

let output1 = test1('  a  b c d C b A ')
console.log(output);  // --> { a: 2, b: 2, c: 2, d: 1 }
let output2 = test1(" ")
console.log(output); // --> {}

Advertisement

Answer

So the idea basically is check if the object exist

  • If yes increment the counter
  • If no create a property and initialize its counter with 1

function objectCount(str) {
  let arr = str.toLowerCase().split(" ");
  let obj = {};

  for (let i = 0; i < arr.length; i++) {
    if (Object.hasOwnProperty.call(obj, arr[i])){
      obj[arr[i]]++;
    } else {
      obj[arr[i]] = 1;

    }
  }
  return obj;
}


let output = objectCount('ask a bunch try a BUNCH get a bunch');
console.log(output); // --> { ask: 1, a: 3, bunch: 3, try: 1, get: 1 };
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement