Check if all values of array are equal

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Check if all values of array are equal



I need to find arrays where all values are equal. What's the fastest way to do this? Should I loop through it and just compare values?


['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false





@T.J.Crowder I bet you are already thinking about the best solution ;)
– VisioN
Feb 12 '13 at 12:31





@T.J.Crowder: Not to mention the willingness of askers to actually accept answers. Users with 1 rep often seem to be ask & run types that leave as soon as they have a copy-paste-able answer, lately.
– Cerbrus
Feb 12 '13 at 12:39






Something around this approach should work ? a.join(',').split(a[0]).length === a.length + 1
– Jashwant
Feb 12 '13 at 12:42


a.join(',').split(a[0]).length === a.length + 1





@TomášZato: "OP" means "original poster" (the person asking the question).
– T.J. Crowder
Feb 12 '13 at 14:38





Possible duplicate of Check if each item in an array is identical in javascript
– Anderson Green
Feb 14 '17 at 4:32




27 Answers
27


const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] ) // true



Or one-liner:


[1,1,1,1].every( (val, i, arr) => val === arr[0] ) // true



Array.prototype.every (from MDN) :
The every() method tests whether all elements in the array pass the test implemented by the provided function.





Brevity is the soul of wit
– svarog
Jul 6 '16 at 7:36





Best use of language.
– SoEzPz
Nov 17 '17 at 16:40





I have created a jsperf case. This method outperforms most candidates.
– Junliang Huang
Jan 18 at 4:44





const everythings_equal = array => array.every(thing => thing === array[0]);
– K._
Jan 25 at 11:24


const everythings_equal = array => array.every(thing => thing === array[0]);



Edit: Be a Red ninja:


!!array.reduce(function(a, b) return (a === b) ? a : NaN; );



Results:


var array = ["a", "a", "a"] => result: "true"
var array = ["a", "b", "a"] => result: "false"
var array = ["false", ""] => result: "false"
var array = ["false", false] => result: "false"
var array = ["false", "false"] => result: "true"
var array = [NaN, NaN] => result: "false"



Warning:


var array = => result: TypeError thrown



This is because we do not pass an initialValue. So, you may wish to check array.length first.


array.length





might be a bit late to the party... i think this doesn't work if your array is made of falses! for example try [false, false, false].reduce(function(a, b)return (a === b)?a:false;);
– George Flourentzos
Nov 27 '14 at 19:21



false





@Martin: ["false", ""] returns true :/
– dalgard
Oct 15 '15 at 16:55



["false", ""]


true





This can be taken up a notch by using NaN. Since both NaN === NaN and NaN !== NaN are false, it guarantees that once the prev is set to NaN then no value can take it out. Also adding in a double negation converts the results to true and false, since NaN is falsy. Final form: !!array.reduce(function(a, b) return (a === b) ? a : NaN; );
– Filipe Silva
Jan 19 '16 at 17:53



NaN


NaN === NaN


NaN !== NaN


prev


true


false


NaN


!!array.reduce(function(a, b) return (a === b) ? a : NaN; );





DOWNVOTED. What if the elements are equal but falsy?
– K._
Jan 25 at 9:52






I downvoted because this doesn't work with booleans values.
– Tyguy7
Apr 3 at 22:10



This works. You create a method on Array by using prototype.


Array.prototype.allValuesSame = function()

for(var i = 1; i < this.length; i++)

if(this[i] !== this[0])
return false;


return true;



Call this in this way:


var a = ['a', 'a', 'a'];
var b = a.allValuesSame(); //true
a = ['a', 'b', 'a'];
b = a.allValuesSame(); //false





very nice, but beware: IE does not support this way of assigning prototypes. I use it anyway.
– Tomáš Zato
Feb 12 '13 at 12:34





You don't need the else block in there, because the if will return a value from the function, before the code below it has a chance to be executed, if the condition in the if is true. If it's false, the else should be executed any way, no need to wrap it in extra 's
– Cerbrus
Feb 12 '13 at 12:43


else


if


if


true


false


else






@TomášZato: IE supports augmenting the Array.prototype just fine (even IE6). It's only DOM element prototypes that some older versions of IE don't support augmenting.
– T.J. Crowder
Feb 12 '13 at 13:00


Array.prototype





I don't think it's a good idea to be monkey patching built-in prototypes. If multiple libraries do it, it can lead to unexpected behavior that's very difficult to debug.
– Mark Wilbur
Dec 12 '14 at 7:33





@MarkWilbur +1 especially if you do a for..in loop on next arrays, you'll get allValuesSame in the loop
– Olivier Pons
Apr 23 '16 at 9:14


allValuesSame



In JavaScript 1.6, you can use Array.every:


Array.every


function AllTheSame(array)
var first = array[0];
return array.every(function(element)
return element === first;
);



You probably need some sanity checks, e.g. when the array has no elements. (Also, this won't work when all elements are NaN since NaN !== NaN, but that shouldn't be an issue... right?)


NaN


NaN !== NaN





Dat ugly copy/paste of all/any functions of Python...
– Olivier Pons
Apr 23 '16 at 8:46



You can turn the Array into a Set. If the size of the Set is equal to 1, then all elements of the Array are equal.


function allEqual(arr)
return new Set(arr).size == 1;


allEqual(['a', 'a', 'a', 'a']); // true
allEqual(['a', 'a', 'b', 'a']); // false





Brilliant. Just note that allEqual([NaN, NaN]) gives true in this case.
– K._
Jan 25 at 11:26



allEqual([NaN, NaN])


true



And for performance comparison I also did a benchmark:


function allAreEqual(array)
if(!array.length) return true;
// I also made sure it works with [false, false] array
return array.reduce(function(a, b)return (a === b)?a:(!b);) === array[0];

function same(a)
if (!a.length) return true;
return !a.filter(function (e)
return e !== a[0];
).length;


function allTheSame(array)
var first = array[0];
return array.every(function(element)
return element === first;
);


function useSome(array)
return !array.some(function(value, index, array)
return value !== array[0];
);



Results:


allAreEqual x 47,565 ops/sec ±0.16% (100 runs sampled)
same x 42,529 ops/sec ±1.74% (92 runs sampled)
allTheSame x 66,437 ops/sec ±0.45% (102 runs sampled)
useSome x 70,102 ops/sec ±0.27% (100 runs sampled)



So apparently using builtin array.some() is the fastest method of the ones sampled.





Good idea to check what's more performant here. The reason why Array#some is going to sometimes outperform is that once the callback function returns true, it stops iterating. So, if all the elements are in fact equal, the performance should be identical to Array#every. And the relative performance when all elements are not equal will vary based on the index of the first non-matching element.
– danmactough
Jan 6 '15 at 12:09


Array#some


Array#every





Nice one. You could have named each with the function used lol. E.g.: reduce, filter, every, some
– Z. Khullah
Aug 2 '17 at 15:54



Shortest answer using underscore/lodash


function elementsEqual(arr)
return !_.without(arr, arr[0]).length



spec:


elementsEqual(null) // throws error
elementsEqual() // true
elementsEqual() // true
elementsEqual([1]) // true
elementsEqual([1,2]) // false
elementsEqual(NaN) // true



edit:



Or even shorter, inspired by Tom's answer:


function elementsEqual2(arr)
return _.uniq(arr).length <= 1;



spec:


elementsEqual2(null) // true (beware, it's different than above)
elementsEqual2() // true
elementsEqual2() // true
elementsEqual2([1]) // true
elementsEqual2([1,2]) // false
elementsEqual2(NaN) // true



If you're already using underscore.js, then here's another option using _.uniq:


_.uniq


function allEqual(arr)
return _.uniq(arr).length === 1;



_.uniq returns a duplicate-free version of the array. If all the values are the same, then the length will be 1.


_.uniq



As mentioned in the comments, given that you may expect an empty array to return true, then you should also check for that case:


true


function allEqual(arr) _.uniq(arr).length === 1;





But if array is empty, your answer will return false. While I think it should be true. Changing to .length <= 1 shall be enough though.
– average Joe
Mar 22 '17 at 11:43



false


true


.length <= 1





@Kasztan that's a fair point. I've updated my answer to cover that case.
– Tom Fenech
Mar 22 '17 at 13:29



Yes, you can check it also using filter as below, very simple, checking every values are the same as the first one:


//ES6
function sameValues(arr)
return arr.filter((v,i,a)=>v===a[0]).length === arr.length;



also can be done using every method on the array:


//ES6
function sameValues(arr)
return arr.every((v,i,a)=>v===a[0]);



and you can check your arrays like below:


sameValues(['a', 'a', 'a', 'a']); // true
sameValues(['a', 'a', 'b', 'a']); // false



Or you can add it to native Array functionalities in JavaScript if you reuse it a lot:


//ES6
Array.prototype.sameValues = Array.prototype.sameValues || function()
this.every((v,i,a)=>v===a[0]);



and you can check your arrays like below:


['a', 'a', 'a', 'a'].sameValues(); // true
['a', 'a', 'b', 'a'].sameValues(); // false



You can use Array.every if supported:


Array.every


var equals = array.every(function(value, index, array)
return value === array[0];
);



Alternatives approach of a loop could be something like sort


sort


var temp = array.slice(0).sort();
var equals = temp[0] === temp[temp.length - 1];



Or, if the items are like the question, something dirty like:


var equals = array.join('').split(array[0]).join('').length === 0;



Also works.





Thank you for putting all answers in one...
– Tomáš Zato
Feb 12 '13 at 13:05





You have the first example backwards. Should be equals = !array.some( (v,i,a) => v!==a[0] ). Otherwise you're just checking that any value equals the first which will, of course, always be true :)
– Mark Kahn
Jul 30 '15 at 4:53


equals = !array.some( (v,i,a) => v!==a[0] )





Not exactly, I used some instead of every as I mentioned in the first paragraph. :) Thanks for the catch!
– ZER0
Aug 2 '15 at 15:39



some


every



You can get this one-liner to do what you want using Array.prototype.every, Object.is, and ES6 arrow functions:


const all = arr => arr.every(x => Object.is(arr[0], x));





Please, describe the solution you're proposing.
– il_raffa
Dec 29 '15 at 10:26



I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.



given an array data, then you can use:


for(x=0;x<data.length - 1;x++)
if (data[x] != data[x+1])
isEqual = false;


alert("All elements are equal is " + isEqual);





This might be the fastest solution: jsperf.com/array-equal-values
– Tieme
Feb 9 '16 at 12:18


arr.length && arr.reduce(function(a, b)return (a === b)?a:false;) === arr[0];



You can use this:


function same(a)
if (!a.length) return true;
return !a.filter(function (e)
return e !== a[0];
).length;



The function first checks whether the array is empty. If it is it's values are equals..
Otherwise it filter the array and takes all elements which are different from the first one. If there are no such values => the array contains only equal elements otherwise it doesn't.



Something around this approach should work.


a.join(',').split(a[0]).length === a.length + 1





I upvoted a while ago, and then realized that this would report the following as all the same: ["a", "b", "aa"]. Bummer!
– Scott Sauyet
Feb 12 '13 at 14:02






Yep it sure does. Bummer.
– Robert Fricke
Feb 12 '13 at 15:03





@ScottSauyet Nice catch, I didnt think much about it and thus said, something around this approach. Btw, it suits OP's need as it looks to me that all array elements are chars.
– Jashwant
Feb 12 '13 at 17:31




Update new solution: check index


let a = ['a', 'a', 'b', 'a'];
let a = ['a', 'a', 'a', 'a'];
let check = (list) => list.every(item => list.indexOf(item) === 0);
check(a); // false;
check(b); // true;



Updated with ES6:
Use list.every is the fastest way:


list.every


let a = ['a', 'a', 'b', 'a'];
let check = (list) => list.every(item => item === list[0]);



old version:


var listTrue = ['a', 'a', 'a', 'a'];
var listFalse = ['a', 'a', 'a', 'ab'];

function areWeTheSame(list)
var sample = list[0];
return (list.every((item) => item === sample));



Underscore's _.isEqual(object, other) function seems to work well for arrays. The order of items in the array matter when it checks for equality. See http://underscorejs.org/#isEqual.


_.isEqual(object, other)



Well, this is really not very complicated. I have strong suspicion you didn't even try. What you do is that you pick the first value, save it in the variable, and then, within a for loop, compare all subsequent values with the first one.
I intentionally didn't share any code. Find how for is used and how variables are compared.


for


for





this should be accepted one.
– alix
Apr 25 '13 at 14:32





I don't like this answer. It wouldn't let you know if the second value was the same as the third, etc. Obviously nested loop would do it, but that's conceptually different to a novice scripter.
– jtromans
Aug 20 '13 at 16:42






@jtromans: because of the transitive property of equality, if A==B and A==C then we know B==C; you don't have to verify it "manually" with a nested loop etc. Repeating comparison against a single value (first value in the array, not an arbitrary one :) is exactly what this answer suggests and so does the accepted answer.
– o.v.
Aug 29 '13 at 23:53






It's not complicated. And neither are the other answers on the page. But to me, this answer is by far the least helpful.
– Charlie
Jan 24 '15 at 23:00





It was originally meant to make a strong point towards the OP insisting he tries to think before asking questions.
– Tomáš Zato
Jan 24 '15 at 23:48


var listTrue = ['a', 'a', 'a', 'a'];
var listFalse = ['a', 'a', 'a', 'ab'];

function areWeTheSame(list)
var sample = list[0];
return !(list.some(function(item)
return !(item == sample);
));





Please also explain what you did instead of just pasting some code.
– Wouter J
May 4 '15 at 11:16



Its Simple.
Create a function and pass a parameter.
In that function copy the first index into a new variable.
Then Create a for loop and loop through the array.
Inside a loop create an while loop with a condition checking whether the new created variable is equal to all the elements in the loop.
if its equal return true after the for loop completes else return false inside the while loop.


function isUniform(arra)
var k=arra[0];
for (var i = 0; i < arra.length; i++)
while(k!==arra[i])
return false;


return true;



Simple one line solution, just compare it to an array filled with the first entry.


if(arr.join('') === Array(arr.length).fill(arr[0]).join(''))





That doesn't seem like a solution that can be used anywhere
– Lu4
Sep 22 '16 at 10:05





It's pretty close to ok. Better would be something like: function arrayOfSame(arr) return (arr.join('') == (new Array(arr.length+1).join(arr[0])));
– Arkain
Mar 15 '17 at 15:57




Another interesting way when you use ES6 arrow function syntax:


x = ['a', 'a', 'a', 'a']
!x.filter(e=>e!==x[0])[0] // true

x = ['a', 'a', 'b', 'a']
!x.filter(e=>e!==x[0])[0] // false

x =
!x.filter(e=>e!==x[0])[0] // true



And when you don't want to reuse the variable for array (x):


!['a', 'a', 'a', 'a'].filter((e,i,a)=>e!==a[0])[0] // true



IMO previous poster who used array.every(...) has the cleanest solution.


function isUniform(array)
for (var i=1; i< array.length; i++)
if (array[i] !== array[0]) return false;


for (var i=1; i< array.length; i++)
if (array[i] === array[0]) return true;




this might work , you can use the comment out code as well that also woks well with the given scenerio.




function isUniform()
var arrayToMatch = [1,1,1,1,1];
var temp = arrayToMatch[0];
console.log(temp);
/* return arrayToMatch.every(function(check)
return check == temp;
);*/
var bool;
arrayToMatch.forEach(function(check)
bool=(check == temp);
)
console.log(bool);

isUniform();



Another way with delimited size and organized list:



array1 = [1,2,3];
array2 = [1,2,3];


function isEqual()

return array1.toString()==array2.toString();



The every() method checks if all elements in an array pass a test (provided as a function).



The every() method executes the function once for each element present in the array:



Note: every() does not execute the function for array elements without values.



Note: every() does not change the original array




var ages = [32, 33, 16, 40];

function checkAdult(age)
return age == 1;


function myFunction()
alert(ages.every(checkAdult));


<p>Click the button to check if every element in the array is equal to one.</p>

<button onclick="myFunction()">Try it</button>



In PHP, there is a solution very simple, one line method :



(count(array_count_values($array)) == 1)



For example :


$arr1 = ['a', 'a', 'a', 'a'];
$arr2 = ['a', 'a', 'b', 'a'];


print (count(array_count_values($arr1)) == 1 ? "identical" : "not identical"); // identical
print (count(array_count_values($arr2)) == 1 ? "identical" : "not identical"); // not identical



That's all.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS