I'm trying to resolve this problem, where I need to check if every element of an array has the same type, I need to do it with the method "every". but I don't know why my code does not work, could you help me, please? Thanks
function allSameType(i) {
return (typeof i === typeof i[0]);
}
const c = [1, 2, 3];
const d = [1, 2, 3, "4"];
console.log(c.every(allSameType));
console.log(d.every(allSameType));
The expected output should be True and False, but I'm getting both False
You are trying to access the first element passed in the allSameType as an array, but it is not the array but an element of the array.
You can pass the array to the allSameType() function as a third parameter, because the Array.prototype.every callback accepts three arguments:
i)_)arr)function allSameType(i, _, arr) {
return (typeof i === typeof arr[0]);
}
const c = [1, 2, 3];
const d = [1, 2, 3, "4"];
console.log(c.every(allSameType));
console.log(d.every(allSameType));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With