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)
Using == on array will not give the desired result and it will compare them as objects.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With