Data Scientist
Data Scientist

Reputation: 5

Split and Objects - JavaScript

I am writing a function called "countStr".

I need to return an object where each key is a word in the given string, with its value being how many times that word appeared in the given string. If the string is empty it must return an empty object.

Here's my function so far:

function countStr(str) {
   myObject = {};
  if(str.length === 0) {
    return myObject;
  } else {
    myArray = str.split(' ');
    for(var i = 0; i < myArray; i++) {
      var key = myArray[i];
      if(myObject.hasOwnProperty(key)) {
        myObject[key]++;
      } else {
        myObject[key];
      }
    }
    return myObject;
  }
}

var output = countStr('ask me lots get me lots'); 
console.log(output); // --> IT MUST OUTPUT {ask: 1, me: 2, lots: 2, get: 1}

Can you tell me how to fix it?

Upvotes: 0

Views: 45

Answers (3)

Manikandan Velayutham
Manikandan Velayutham

Reputation: 2228

function countStr(str) {
   myObject = {};
   var myArray = [];
  if(str.length === 0) {

    return myObject;
  } else {
   myArray = str.split(' ');
    for(var i = 0; i < myArray.length; i++) {
      var key = myArray[i];
      if(myObject.hasOwnProperty(key)) {
     myObject[key]++;     
      } else {     
      myObject[key]=1;
      }
    }
    return myObject;
  }
}

var output = countStr('ask me lots get me lots'); 
console.log(output);

Upvotes: 0

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

There are small issues with your code.

  1. You need to iterate from zero to the length of the array.
  2. You need to initialize the object items with 1 in the else case.
  3. You should use local variables with the var to avoid polluting your top level namespace.

Here is the fixed version:

function countStr(str) {
  var myObject = {};
  if(str.length === 0) {
    return myObject;
  } else {
    var myArray = str.split(' ');
    for(var i = 0; i < myArray.length; i++) {
      var key = myArray[i];
      if(myObject.hasOwnProperty(key)) {
        myObject[key]++;
      } else {
        myObject[key] = 1;
      }
    }
    return myObject;
  }
}

var output = countStr('ask me lots get me lots');
console.log(output);

Upvotes: 2

Weedoze
Weedoze

Reputation: 13943

You can use Array#reduce() like this

function countStr(str) {
  return str.trim().length ? str.split(' ').reduce((o,s)=>{
    o[s] = o[s] || 0;
    o[s]++;
    return o;
  }, {}) : {};
}

var output = countStr('ask me lots get me lots');
console.log(output); // --> {ask: 1, me: 2, lots: 2, get: 1}

Other wise in your code, you were missing Array.length in your for condition and the else should be like myObject[key]=1

Upvotes: 1

Related Questions