Count how many times each word in a string - Help

Hi everyone

I have been trying my hardest this whole day to solve this problem but I’m stuck and don’t want to find the answer on google.

I know that there will be easier and simpler solutions but I wanted to stick with the way I wanted to solve.
Please help find and correct my mistakes in this code:

function reachZeroPosition(arrTemp, arrOrig, i) {
  for (var k = 0; k < arrTemp.length; k++) {
    if (arrTemp.indexOf(arrOrig[i]) !== 0) {
      var a = arrTemp.shift();
    }
  }
  return arrTemp;
}

function countWords(str) {
  var words = str.split(" ");
  var temp = [];
  var result = [];
  var fResult = [];
  var found;
  var count = 0;

  for (var j = 0; j < words.length; j++) {
    temp = words.slice();
    found = temp.indexOf(words[j]);

    for (var i = 0; i < words.length; i++) {
      if (found !== -1) {
        temp = reachZeroPosition(temp, words, j);
        if (count === 0) {
          result[j] = temp.shift();
        }
        result[j + 1] = ++count;
      } else {
        break;
      }
      found = temp.indexOf(words[j]);
    }

    count = 0;
    fResult.push(result);
  }
  return fResult;
}

countWords("ask a bunch get a bunch");

Here’s an explanation of what I have done:

1- Converted String to array of words.
2- Copied the array to a temp array.
3- This temp will be shortened by the function above to make the desired word at position 0.
4- I keep track of Count and store both word and count in an array.
5- temp will be updated from words for each word.
6- words is never changed that’s why I used slice to copy.
6- I push the result to a final array.

There’s an issue in the logic, I tried debugging but I got nowhere

Please help

What do you think? @KoniKodes @lasjorg @shimphillip

Yeah that’s exactly what I have been doing

It’s okay but I tried to maintain the same order of words in the final result

But as a beginner I could not reach such a short and optimized answer unfortunately
Is there any way to debug my code and get it to work?

Thanks for your response
I’ll try to come up with an algorithm and see if I could solve this basic problem or not

@OmarDulaimi

I think the problem is in the scope of the functions.
Where do you store arrTemp and arrOrig? and How do you get them into countWords?