11

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)

Dan Prince
  • 29,491
  • 13
  • 89
  • 120
cytsunny
  • 4,838
  • 15
  • 62
  • 129

7 Answers7

6

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

Community
  • 1
  • 1
Matt D. Webb
  • 3,216
  • 4
  • 29
  • 51
5

Suppose you have:

const xs = [1,2,3];
const ys = [3,2,1];

This seems to work:

xs.every(x => ys.includes(x));
//=> true

But it gives you false positives:

const xs = [2,2,2];
const ys = [1,2,3];

xs.every(x => ys.includes(x));
//=> true

// But…
ys.every(y => xs.includes(y));
//=> false

Another example:

const xs = [2];
const ys = [1,2,3];

xs.every(x => ys.includes(x));
//=> true

// But…
ys.every(y => xs.includes(y));
//=> false

We could compare the size of both arrays and bail out quickly but technically these two arrays do contain the same elements:

const xs = [2];
const ys = [2,2,2];

ys.every(y => xs.includes(y));
//=> true

xs.every(x => ys.includes(x));
//=> true

The way I would answer this question is by computing the set of unique values for both arrays.

const similar = (xs, ys) => {
  const xsu = [...new Set(xs).values()]; // unique values of xs
  const ysu = [...new Set(ys).values()]; // unique values of ys
  return xsu.length != ysu.length ? false : xsu.every(x => ysu.includes(x));
}

similar([1,2,3],[3,2,1]);
//=> true

similar([2,2,2],[3,2,1]);
//=> false

similar([2],[3,2,1]);
//=> false

similar([2],[2,2,2]);
//=> true

similar([1,2,3],[4,5,6]);
//=> false
customcommander
  • 17,580
  • 5
  • 58
  • 84
2

Using Vanilla JavaScript

Supported in all modern browsers you can use Array.prototype.every()

ECMAScript 2016

let firstArray  = [1, 2, 3, 4, 5];
let secondArray = [5, 4, 3, 2, 1];
let Equals = firstArray.every((item)=>secondArray.includes(item))
alert("Equals? " + Equals)

Internet Explorer Support

Internet Explorer does not have access to Array.prototype.includes(). If you need it to run in Internet Explorer you can use indexOf

let firstArray  = [1, 2, 3, 4, 5];
let secondArray = [5, 4, 3, 2, 1];
let Equals = firstArray.every(function (item){return secondArray.indexOf(item) > -1})
alert("Equals? " + Equals)

This will iterate through every item in firstArray and check if the value is contained within secondArray, and return true only if the function returns true for Every item

Do note that the given function will work for this question, But is Non Recursive and only works with primitive types on two Flat arrays, If you want to compare non-primitives you will need to modify the compare function to compare your Object structure

Ethan Snow
  • 447
  • 2
  • 10
  • ES2016 example still reports true if secondArray has additional values. Adding a check for firstArray.length === secondArray.length should fix that. – dangerginger Jul 17 '22 at 04:34
1

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.

Community
  • 1
  • 1
Siguza
  • 21,155
  • 6
  • 52
  • 89
  • 1
    Array.sort() modifies the actual array. It's worth cloning the array, then sorting it, and then checking each element iteratively. – shmuli Apr 15 '15 at 10:58
-1

Here's a working implementation using Vanilla JS:

function haveMatchingElements(firstArray, secondArray) {
    var stringsInFirstArray = parse(firstArray, 'string'),
        stringsInSecondArray = parse(secondArray, 'string'),
        numbersInFirstArray = parse(firstArray, 'number'),
        numbersInSecondArray = parse(secondArray, 'number'),
        stringResults = compare(stringsInFirstArray, stringsInSecondArray),
        numberResults = compare(numbersInFirstArray, numbersInSecondArray);

    if (stringResults && numberResults) {
        return true;
    } return false;

    function parse(array, type) {
        var arr = [];
        arr = array.sort().filter(function(index) {
            if (typeof index == type)
                return index;
        });
        return arr;
    }

    function compare(firstArray, secondArray) {
        if (firstArray.length !== secondArray.length)
            return false;
        for (var i = firstArray.length; i--;) {
            if (firstArray[i] !== secondArray[i])
                return false;
        }
        return true;
    }
}

This parses strings an numbers into different arrays and checks them separately. That will correct the issue of 1 and "1" matching as true due to the implicit type conversion caused by the sort function.

The implementation is simple:

var arr1 = ['1', 1];
var arr2 = [1, '1'];

var results = haveMatchingElements(arr1, arr2);
console.log(results); // true  
shmuli
  • 5,086
  • 4
  • 32
  • 64
-1

This is how you can verify if two arrays have exactly the same elements and in the same order in ES6:

const array1 = [1, 2, 7, 9];
const array2 = [2, 1, 3]

const arraysWithSameValuesAndOrder = (array1, array2) => {
    return array1.every((item) => array1.indexOf(item) === array2.indexOf(item)) && Boolean(array1.length === array2.length)
  }

const res = arraysWithSameValuesAndOrder(array1, array2)
console.log('res', res) FALSE
roniccolo
  • 99
  • 1
  • 5
  • OP asked about a method where you compare two arrays which have the same elements but in DIFFERENT ORDER. – Andor Németh Oct 11 '21 at 06:57
  • because the point of the question is that it should not be compared whether they are in the same order or not but your function is literally called "arraysWithSaveValuesAndOrder" – Andor Németh Oct 18 '21 at 09:36
-2

Not in Vanila Javascript but in Angular there is option to match two objects.

angular.equals([1,2,3],[1,2,3])

Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects.

See if this could help you.

alert("Match result of [1,2,3] &  [1,2,3] is "+angular.equals([1,2,3],[1,2,3]));

alert("Match result of [1,4,3] &  [1,2,3] is "+angular.equals([1,4,3],[1,2,3]));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Click on Run Code snippet. If this solves your need please mark it as as Answer :)

In case order is not important and array is of number type.

var a1 = [1, 2, 3];
var a2 = [2, 1, 3];
//In case order is not important and array is of number type.
alert(eval(JSON.stringify(a1).replace(/,/g, "+").replace(/\[/g, "").replace(/\]/g, "")) === eval(JSON.stringify(a2).replace(/,/g, "+").replace(/\[/g, "").replace(/\]/g, "")));
Sam4Code
  • 541
  • 5
  • 9
  • Try `[1, 2, 3]` and `[3, 2, 1]`. OP wants `true` for this case. – thefourtheye Apr 15 '15 at 11:06
  • in that case you can directly go for plain Javascript code. var a1 = [1, 2, 3]; var a2 = [2, 1, 3]; alert(eval(JSON.stringify(a1).replace(/,/g, "+").replace(/\[/g, "").replace(/\]/g, "")) === eval(JSON.stringify(a2).replace(/,/g, "+").replace(/\[/g, "").replace(/\]/g, ""))); – Sam4Code Apr 15 '15 at 11:31
  • Comparing an array by string is a poor way. See http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript – cytsunny Apr 16 '15 at 02:10