How to Know If Two Arrays Have the Same Values

How to know if two arrays have the same values

Sort the arrays and compare their values one by one.

function arrayCompare(_arr1, _arr2) {
if (
!Array.isArray(_arr1)
|| !Array.isArray(_arr2)
|| _arr1.length !== _arr2.length
) {
return false;
}

// .concat() to not mutate arguments
const arr1 = _arr1.concat().sort();
const arr2 = _arr2.concat().sort();

for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}

return true;
}

How to check if two arrays contain the same values?

I would do array_diff() which check difference between two arrays.

$areEqual = array_diff($a, $b) === array_diff($b, $a);

or

$areEqual = !(array_diff($a, $b) || array_diff($b, $a));

Is there a way to check if two arrays have the same elements?

Using jQuery

You can compare the two arrays using jQuery:

// example arrays:
var firstArray = [ 1, 2, 3, 4, 5 ];
var secondArray = [ 5, 4, 3, 2, 1 ];

// compare arrays:
var isSameSet = function( arr1, arr2 ) {
return $( arr1 ).not( arr2 ).length === 0 && $( arr2 ).not( arr1 ).length === 0;
}

// get comparison result as boolean:
var result = isSameSet( firstArray, secondArray );

Here is a JsFiddle Demo

See this question helpful answer

Check if two arrays have the same values

sort($a);
sort($b);
if ($a===$b) {//equal}

How to check if two arrays contain the same elements?

If the elements should be equal and in the same order, you can just compare the arrays with =.

If the elements should be equal and the order does not matter and there are no duplicates to be expected, use array1 asSet = arr2 asSet.

Otherwise you can check out hasEqualElements:, and asBag as well.

If the elements should be identical and in the same order, how about this?

array1 with: array2 do:
[ :a :b | a == b ifFalse: [ ^ false ]].
^ true

It iterates over the two arrays simultaneously, comparing the identities of elements at the same indices. If any are not identical, return false. If no distinct elements were encountered, return true.

How to check if Two Arrays Have Same Elements Regardless of Their Index Position

Use Array Diff :

$a = array("apple","banana", "strawberry");
$b = array("strawberry", "apple","banana");


$result = array_diff($a, $b);

if(count($result) > 0){
echo "yes";
}else{
echo "no";
}

PHP - Check if two arrays are equal

$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

See Array Operators.

EDIT

The inequality operator is != while the non-identity operator is !== to match the equality
operator == and the identity operator ===.



Related Topics



Leave a reply



Submit