You're returning a value from the forEach
function, but that doesn't mean you're returning a value from the isThree
function. Also, try the filter
function to find if there is a match for the number you're looking for.
Try this:
function isThree(...args){
return args.filter(val => {
if(val === 3){
return true;
}
}).length > 0;
};
console.log(isThree(1,2,3,4,5));
In the previous example, I'm using filter
to return every instance of the array in which the condition is met (in this case, val === 3
). Returning true
appends the result to an empty array, so the operation's response will be an array with every instance that met the condition. So by comparing the array size to > 0
I can find out if any element met the criteria.
You can even reduce the function further by using the shorthand args.filter(val => val === 3)
:
function isThree(args){
return args.filter(val => val === 3).length > 0;
};
console.log(isThree(1,2,3,4,5));
Or, you can simplify further by using the prototype function some
, which checks if any element of the array meets the criteria:
function isThree(args){
return args.some(val => val === 3);
};
console.log(isThree(1,2,3,4,5));