Check 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 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.

Check if two arrays have the same values (regardless of value order)

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

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

How can I find matching values in two arrays?

Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.

​Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};


My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:

Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};

Usage would look like:

var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

console.log(array1.diff(array2));

If you have an issue/problem with extending the Array prototype, you could easily change this to a function.

var diff = function(arr, arr2) {

And you'd change anywhere where the func originally said this to arr2.

How to check if two arrays have the same set of digits in C?

You have several ways you can approach this, you can use two sets of nested loops swapping the order you loop over the two arrays validating each element is found in the other. Two full sets of nested loops are needed as you have a 50/50 chance any single outlier will be contained in either of the arrays. This is the brute-force method and has the potential worst-case number of iterations.

Since an outlier is what drove the need for looping with one arrays as outer and the other inner and then swapping a repeating, e.g. to catch 5, 1, 2, 3, 3, 4, 6, 1 and 1, 2, 3, 4, 5, 6, 7, if you can catch the outlier with another method that requires fewer iterations you can make your algorithm more efficient.

An outlier would be detected in a comparison of the min and max from each array, and to find min and max only requires a single linear traversal of each array. Much better than the worst-case nested loop over all elements.

The min and max check provide a way to shorten your work, but do not eliminate the need to press forward with a second set of nested loops if the result is inconclusive at that point. Why? Consider the following sets, where the min and max are equal, but one element within the range is not included in both arrays, e.g.:

    int a[] = { 5, 1, 2, 3, 3, 4, 6, 112 },
b[] = { 1, 2, 3, 4, 5, 6, 7, 112 };

The only way the 7 will be detected is by nested loop with the array containing 7 being the outer loop.

So you could write a short function to test for the common set as:

#include <stdio.h>
#include <limits.h>

int commonset (int *a, int *b, int sza, int szb)
{
int maxa = INT_MIN, maxb = INT_MIN,
mina = INT_MAX, minb = INT_MAX;

for (int i = 0; i < sza; i++) { /* find max/min of elements of a */
if (a[i] > maxa)
maxa = a[i];
if (a[i] < mina)
mina = a[i];
}
for (int i = 0; i < szb; i++) { /* find max/min of elements of b */
if (b[i] > maxb)
maxb = b[i];
if (b[i] < minb)
minb = b[i];
}

if (maxa != maxb || mina != minb) /* validate max & mins equal or return 0 */
return 0;

for (int i = 0; i < sza; i++) { /* compare of each element between arrays */
int found = 0;
for (int j = 0; j < szb; j++)
if (a[i] == b[j]) {
found = 1;
break;
}
if (!found)
return 0;
}

for (int i = 0; i < szb; i++) { /* compare of each element between arrays */
int found = 0;
for (int j = 0; j < sza; j++)
if (a[j] == b[i]) {
found = 1;
break;
}
if (!found)
return 0;
}

return 1;
}

Adding a short example program:

int main (void) {

int a[] = { 5, 1, 2, 3, 3, 4, 6, 1 },
sza = sizeof a / sizeof *a,
b[] = { 1, 2, 3, 4, 5, 6 },
szb = sizeof b / sizeof *b,
result;

result = commonset (a, b, sza, szb);
if (result)
puts ("arrays have common set of numbers");
else
puts ("arrays have no common set of numbers");

return result;
}

Example Use/Output

$ ./bin/arr_commonset
arrays have common set of numbers
$ echo $?
1

With b[] = { 1, 2, 3, 4, 5, 6, 7 }:

$ ./bin/arr_commonset
arrays have no common set of numbers
$ echo $?
0

With a[] = { 5, 1, 2, 3, 3, 4, 6, 112 } and b[] = { 1, 2, 3, 4, 5, 6, 7, 112 }:

$ ./bin/arr_commonset
arrays have no common set of numbers
$ echo $?
0

There are probably even ways to combine the two and shave off a few iterations, and, if you have a guaranteed range for your input sets, you can use a simple frequency array for each and then two simple linear iterations would be needed to increment the element that corresponds to the index for each value in the array, and then a third linear iteration over both frequency arrays comparing that like indexes either both are non-zero or both are zero to confirm the common set -- that is left to you.

Look things over and let me know if you have any further questions.

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));

Best way to check if values of two arrays are the same/equal in JavaScript

I'm making the following assumptions:

  • The arrays only contain numbers.
  • You don't care about the order of the elements; rearranging the arrays is OK.

Under those conditions we can simply convert each array to a canonical string by sorting it and joining the elements with e.g. a space. Then (multi-)set equality boils down to simple string equality.

function areValuesTheSame(a, b) {    return a.sort().join(' ') === b.sort().join(' ');}
const result = [1, 3, 8, 77];const same = [8, 3, 1, 77];const diff = [8, 3, 5, 77];
console.log(areValuesTheSame(result, same));console.log(areValuesTheSame(result, diff));


Related Topics



Leave a reply



Submit