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)
}
Array.prototype.includes()is a much better fit. But are you wanting that or are you wanting a count?forloop approach should be comparingeverything[i] === value