Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let say I have 2 arrays

firstArray  = [1, 2, 3, 4, 5];
secondArray = [5, 4, 3, 2, 1];

I want to know if they contain the same elements, while order is not important. I know I can write a function to sort them and then loop through them to check, but is there a pre-built function for this? (not only Vanilla JS, other javascript library is also okay)

like image 783
cytsunny Avatar asked Apr 15 '15 10:04

cytsunny


People also ask

Can you use == to compare arrays?

Using == on array will not give the desired result and it will compare them as objects.


2 Answers

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

like image 55
Matt D. Webb Avatar answered Sep 30 '22 23:09

Matt D. Webb


Well there is an Array.sort() method in JavaScript, and for comparing the (sorted) arrays, I think it's best to check out this question, as it is has a really good answer.

Especially note that comparing arrays as strings (e.g. by JSON.stringify) is a very bad idea, as values like "2,3" might break such a check.

like image 29
Siguza Avatar answered Sep 30 '22 23:09

Siguza