Check If All Values in Array Are the Same

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

Check if all values of array are of the same type

You could create a Set from the types of each element in the array and make sure that it has at most one element:

console.log( allSameType( [1,2,3,4] ) );console.log( allSameType( [2,3,4,"foo"] ) );
function allSameType( arr ) { return new Set( arr.map( x => typeof x ) ).size <= 1;}

Check if all values in array are the same

All values equal the test value:

// note, "count(array_flip($allvalues))" is a tricky but very fast way to count the unique values.
// "end($allvalues)" is a way to get an arbitrary value from an array without needing to know a valid array key. For example, assuming $allvalues[0] exists may not be true.
if (count(array_flip($allvalues)) === 1 && end($allvalues) === 'true') {

}

or just test for the existence of the thing you don't want:

if (in_array('false', $allvalues, true)) {

}

Prefer the latter method if you're sure that there's only 2 possible values that could be in the array, as it's much more efficient. But if in doubt, a slow program is better than an incorrect program, so use the first method.

If you can't use the second method, your array is very large, and the contents of the array is likely to have more than 1 value (especially if the 2nd value is likely to occur near the beginning of the array), it may be much faster to do the following:

/**
* Checks if an array contains at most 1 distinct value.
* Optionally, restrict what the 1 distinct value is permitted to be via
* a user supplied testValue.
*
* @param array $arr - Array to check
* @param null $testValue - Optional value to restrict which distinct value the array is permitted to contain.
* @return bool - false if the array contains more than 1 distinct value, or contains a value other than your supplied testValue.
* @assert isHomogenous([]) === true
* @assert isHomogenous([], 2) === true
* @assert isHomogenous([2]) === true
* @assert isHomogenous([2, 3]) === false
* @assert isHomogenous([2, 2]) === true
* @assert isHomogenous([2, 2], 2) === true
* @assert isHomogenous([2, 2], 3) === false
* @assert isHomogenous([2, 3], 3) === false
* @assert isHomogenous([null, null], null) === true
*/
function isHomogenous(array $arr, $testValue = null) {
// If they did not pass the 2nd func argument, then we will use an arbitrary value in the $arr (that happens to be the first value).
// By using func_num_args() to test for this, we can properly support testing for an array filled with nulls, if desired.
// ie isHomogenous([null, null], null) === true
$testValue = func_num_args() > 1 ? $testValue : reset($arr);
foreach ($arr as $val) {
if ($testValue !== $val) {
return false;
}
}
return true;
}

Note: Some answers interpret the original question as (1) how to check if all values are the same, while others interpreted it as (2) how to check if all values are the same and make sure that value equals the test value. The solution you choose should be mindful of that detail.

My first 2 solutions answered #2. My isHomogenous() function answers #1, or #2 if you pass it the 2nd arg.

How to check if all values in array are the same?

if is perfectly fine, there is nothing unprofessional about it.

I should note that in short int check[10] = {1,1,1,1,1,1,1,1,1}; only 9 elements are 1, the last element will be initialized to 0, so this check will always be false, if you omit the size i.e. check[] = {1,1,1... you won't have this problem because the size of the array will be deduced by the number of elements in the initializer.

#include <stdio.h>
#include <stdbool.h>

bool aresame(short int a[], size_t n) // added value to check
{
for (size_t i = 1; i < n; i++)
{
if(a[i] != a[0])
return false; // if a different value is found return false
}
return true; // if it reaches this line, all the values are the same
}

int main()
{
short int check[]={1,1,1,1,1,1,1,1,1};
printf("%s", aresame(check, sizeof check / sizeof *check) ? "true" : "false");
}

Live demo

How to check if all of the elements in an array are the same, in matlab?

I think it can be as simple as

if all(v == v(1))

Another method would be

if range(v) == 0

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


Related Topics



Leave a reply



Submit