Check If All Values of Array Are Equal

Check if all values of array are equal

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.

check whether all the values in array is same or not in javascript

Here is one approach to how you might do this. A Set in javascript can only hold unique values, thus, if its size equates to 1, then the array has all equal values, if its size equates to something greater than one, then all the values are not unique:

Take a look at the snippet below:

const aArr = [1, 2, 3, 4, 5];const bArr = [1, 1, 1, 1, 1];
const isUniqueArr = arr => { const tmp = new Set(arr); if(tmp.size > 1) { return false; } return arr[0];}
console.log(isUniqueArr(aArr)); // expected: false
console.log(isUniqueArr(bArr)); // expected: 1

Ruby: check if all array elements are equal

You could also use .uniq, that returns an array with no duplicates, and check the size:

def all_equal?(arr)
arr.uniq.size <= 1
end

How to check if all values in an array are equal

If you want to know if all are equal Enumerable.All is efficient and readable:

string firstItem = StringArray[0];
bool allEqual = StringArray.Skip(1)
.All(s => string.Equals(firstItem, s, StringComparison.InvariantCultureIgnoreCase));

All breaks also on the first comparison that returns false. Note that i've used the static string.Equals to prevent null-reference exceptions on null objects.

By the way, your loop is incorrect since you start to compare at index 2 instead of 1 here:

if(i > 1 ) // indices are zero based
{
// ...
}

fastest way to check if all elements in an array are equal

This algorithm is O(n) which is the fastest way to check all elements of a list because you only have to check each element only one time.

Now just because this is the fastest algorithm in finding if all elements equal a value doesn't mean you have optimized it to its fullest potential.

This then leaves room for a multi-threaded/multiprocessor implementation.

A solution using more cores or threads is splitting the array into the amount of thread/cores you want to process simultaneously i.e. if you have an array of 100 elements and want 10 threads running at the same time-- split the array into 10 pieces and run each section on the array.

Some psudo code:

 int from,to, threadCount = 10;
boolean check[threadCount];

int factor = array.length()/threadCount;
for(int i = 0; i < threadCount; i++){
from = i*factor;
to = i*factor+factor;
newThreadProcess(from, to, array, check[i]);
}

barrier(); //Wait till all the threads are done processing
for(int i = 0; i < threadCount; i++){
if(!check[i]) return false;
}
return true;

This is best when the array is very large

Check if each item in an array is identical in JavaScript

function identical(array) {
for(var i = 0; i < array.length - 1; i++) {
if(array[i] !== array[i+1]) {
return false;
}
}
return true;
}

Check if all the elements of a Julia array are equal

Great question @tparker and great answer @ColinTBowers. While trying to think about them both, it occurred to me to try the straight-forward old-school Julian way-of-the-for-loop. The result was faster on the important input of a long vector of identical elements, so I'm adding this note. Also, the function name allequal seems to be appropriate enough to mention. So here are the variants:

allequal_1(x) = all(y->y==x[1],x)

# allequal_2(x) used to be erroneously defined as foldl(==,x)

@inline function allequal_3(x)
length(x) < 2 && return true
e1 = x[1]
i = 2
@inbounds for i=2:length(x)
x[i] == e1 || return false
end
return true
end

And the benchmark:

julia> using BenchmarkTools

julia> v = fill(1,10_000_000); # long vector of 1s

julia> allequal_1(v)
true

julia> allequal_3(v)
true

julia> @btime allequal_1($v);
9.573 ms (1 allocation: 16 bytes)

julia> @btime allequal_3($v);
6.853 ms (0 allocations: 0 bytes)

UPDATE: Another important case to benchmark is when there is a short-circuit opportunity. So (as requested in commment):

julia> v[100] = 2
2

julia> allequal_1(v),allequal_2(v),allequal_3(v)
(false, false, false)

julia> @btime allequal_1($v);
108.946 ns (1 allocation: 16 bytes)

julia> @btime allequal_3($v);
68.221 ns (0 allocations: 0 bytes)

All things being equal, a for version should get to be allequal in Base.

Check if all elements in an array are equal

All you need to change is the termination condition in the for loop to

i < newArr.Length - 1

so that you can compare array[i] with array[i + 1]. This change makes sure you do not get past the upper bound of the array.



Related Topics



Leave a reply



Submit