Finding out how many times an array element appears has some great answers, and I really like Oriol's answer but can't seem to figure out the logic.
Here it is:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1, 2, 3, 4, 4, 4, 3], 4)); // 3
I've looked at https://www.geeksforgeeks.org/javascript-array-reduce-method/ and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce but I'm afraid I'm still confused by the complexity.
I understand that 0 is the starting total, and that x===1
should be equal to 1 or 0 depending on the truth.
I'm mainly confused with n because I read that n is the return value of the previous function, but there's no previous function in the beginning.