-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)
}
8
  • 2
    If the goal is to check for existence, Array.prototype.includes() is a much better fit. But are you wanting that or are you wanting a count? Commented Jun 9, 2020 at 3: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. Commented Jun 9, 2020 at 3:33
  • @Phil , I am wanting a count, using Array.reduce Commented Jun 9, 2020 at 3:34
  • 2
    FYI, your for loop approach should be comparing everything[i] === value Commented Jun 9, 2020 at 3:38
  • 1
    Cannot reproduce this, it seems to work just fine ~ jsfiddle.net/pkfu09sd Commented Jun 9, 2020 at 3:42

1 Answer 1

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 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.