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)

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one server—search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

👋 Kindness is contagious

DEV works best when you're signed in—unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay