DEV Community

Justin
Justin

Posted on

JS Challenge: Check if all elements in an array are the same

One solution is to verify each element in the array is equal to the first element of the array.

Alternately we can also filter which are not equal to the first element and verify the resulting array length is zero.

arr1 = [1, 1, 1, 1, 1];
arr2 = [1, 1, 0, 1, 1];

arr1.every((e,i,a) => e === a[0]); //returns true
arr2.every((e,i,a) => e === a[0]); //returns false

//OR

arr1.filter((e,i,a) => e !== a[0]).length===0; //returns true
arr2.filter((e,i,a) => e !== a[0]).length===0; //returns false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)