-2

I am trying to replicate the function below using Array.reduce

private getCount = (str, value) => {
var count = 0;
const everything = ['Key1', 'Key2', 'Key3', 'Key4', 'Key5'];
for (let i = 0; i < everything.length; i++) {
  if (everything === value) {
    count++;
  }
}

return count;}

This is my attempt. However, it gives the correct output only when the value is Key1. Could you please suggest what I could be going wrong?

private getCount = (str, value) => {
  const everything = ['Key1', 'Key2', 'Key3', 'Key4', 'Key5'];
  return everything.reduce((accumulator, currentValue, currentIndex, array) => {
    return (currentValue === value ? accumulator + 1 : accumulator)
  }, 0)
}
Phil
  • 157,677
  • 23
  • 242
  • 245
LearnToImprove
  • 345
  • 5
  • 15
  • 2
    If the goal is to check for existence, [`Array.prototype.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) is a much better fit. But are you wanting that or are you wanting a count? – Phil Jun 09 '20 at 03:23
  • @Phil, for me, it works only searching for the first key. Also noted your response about using .includes. However, I am trying to use the reduce function in this scenario, to understand it. – LearnToImprove Jun 09 '20 at 03:33
  • @Phil , I am wanting a count, using Array.reduce – LearnToImprove Jun 09 '20 at 03:34
  • What input values (for `str` and `value`) are you providing and what result do you **expect** to get for each? What results are you actually getting? – Phil Jun 09 '20 at 03:37
  • 2
    FYI, your `for` loop approach should be comparing `everything[i] === value` – Phil Jun 09 '20 at 03:38
  • 1
    Cannot reproduce this, it seems to work just fine ~ https://jsfiddle.net/pkfu09sd/ – Phil Jun 09 '20 at 03:42
  • So do you have an actual problem or not? – Phil Jun 09 '20 at 03:53
  • @Phil, appreciate your help. No, I do not. In my original implementation, I needed a currentValue.trim() === value, which I did not need in the toned down repro that I posted above, which is why I was falsely thinking my implementation does not work. Thanks for your help once again! – LearnToImprove Jun 09 '20 at 04:01

1 Answers1

0

I question why you so badly want to do this using reduce, but the below should get the job done.

everything.reduce((ac, current)=> ac + (current === value ? 1 : 0), 0 );
Devon Page
  • 19
  • 1