Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make this work? Check all elements in array same type, with the method "every"

Tags:

javascript

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

like image 720
Bejotta Avatar asked Dec 01 '25 23:12

Bejotta


1 Answers

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:

  1. The element (i)
  2. The index of the element (_)
  3. The array itself on which it is invoked. (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));
like image 170
Fullstack Guy Avatar answered Dec 04 '25 14:12

Fullstack Guy