Problem looping through an array

Hello,

I am trying to find the occurrences of specific characters in an array, but it seems the function is only looping through the array once as it is picking up the first count of a character, but not the subsequent ones.

Would anyone be able to give me a hint as to what is wrong please?

function trilingualDemocracy(group) {
  let tempArray = group.split("");

  let countD = 0;
  let countF = 0;
  let countI = 0;
  let countR = 0;
  for (let i = 0; i < tempArray.length; i++) {
    if (tempArray[i] == "d") {
      countD++;
    } else if (tempArray[i] == "f") {
      countF++;
    } else if (tempArray[i] == "i") {
      countI++;
    } else if (tempArray[i] == "r") {
      countR++;
    }

    return [countD, countF, countI, countR];
  }
}

console.log(trilingualDemocracy("ffff"));

check where your return is

that was a careless error - many thanks for your help

My loop seems to only be looping once as the count I am getting for ‘r’ in the test data is 1 instead of 2…

Can anyone help please?

function trilingualDemocracy(group) {
  let tempArray = group.split("");
  let countD = 0;
  let countF = 0;
  let countI = 0;
  let countR = 0;

  for (let i = 0; i < tempArray.length; i++) {
    if (tempArray[i] == "d") {
      countD++;
    } else if (tempArray[i] == "f") {
      countF++;
    } else if (tempArray[i] == "i") {
      countI++;
    } else if (tempArray[i] == "r") {
      countR++;
    }
    let countArray = [countD, countF, countI, countR];
    return console.log(countArray);
  }
}
console.log(trilingualDemocracy("rdr"));

your return is inside which block?

1 Like

I had it outside the function and it didn’t seem to be working, but I’ve put it back in and now it seems to be okay. Many thanks for your help though…

a return outside a function doesn’t work no. I meant to point out that you had it inside the loop, you need it outside the loop, but inside the function

thanks…I think it’s sinking in a bit more now…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.