Logo

dev-resources.site

for different kinds of informations.

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

Published at
8/15/2023
Categories
javascript
javascripttips
jschallenge
oneliners
Author
Justin
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

Featured ones: