I'm facing a dilemma with my code involving an array and the .filter
method. It seems like values pushed into the array by another function are being ignored when I try to count them using filters.
Here's a snippet of my code:
var arrToCheck = []
var ones = arrToCheck.filter(function(x) { return x == 1; })
var twos = arrToCheck.filter(function(x) { return x == 2; })
var threes = arrToCheck.filter(function(x) { return x == 3; })
function checkLength(input) {
length = input.length
switch (length) {
case 1:
arrToCheck.push(1)
break;
case 2:
arrToCheck.push(2)
break;
case 3:
arrToCheck.push(3)
break;
default:
console.log ("length too long")
}
}
For example, if the inputs are [A, I, TO, BUT, THE, SHE], then
arrToCheck
should return [1, 1, 2, 3, 3, 3]
ones
should return [1, 1]
.
However, when testing it out, even though arrToCheck
returns including the pushed values correctly, the ones
array remains empty.
The .filter
function does seem to work with manually entered values, but it fails to register the ones pushed by the checkLength
function.
I've attempted converting the 1s from string to number in different places, but no luck so far.
It appears that each component works fine individually, but they don't cooperate well together. What am I missing here?
(Also, as a bonus question, why would an error saying "TRUE isn't a function" occur when a filter function is called?)