Just The Code Please

How to check if two arrays contain the same values in Javascript

January 16th 2024

Summary

Sometimes we need to determine if two arrays contain the same values. This article shows several ways to do that in Javascript.

The Code

Version One

This version is great for arrays of primitive values.

Javascript
function eqArrays(arrayOne,arrayTwo,delimiter) {
    return arrayOne.sort().join(delimiter) === arrayTwo.sort().join(delimiter);
}

const a1 = [1,2,3,4,5];
const a2 = [1,2,3,4,5];

console.log(eqArrays(a1,a2,','));

Version Two

This version is great for arrays of objects.

Javascript
function eqArrays(arrayOne,arrayTwo,compareFunc) {
    for(let a of arrayOne) {
        let doesContain = false;
        for(let b of arrayTwo) {
            if(compareFunc(a,b)) {
                doesContain = true;
                break;
            }
        }
        if(!doesContain) return false;
    }
    return true;
}


const a1 = [
    {id: 1,name:"test"},
    {id: 2,name:"test"},
    {id: 3,name:"test"},
    {id: 4,name:"test"},
    {id: 5,name:"test"}
];
const a2 = [
    {id: 1,name:"test"},
    {id: 2,name:"test"},
    {id: 3,name:"test"},
    {id: 4,name:"test"},
    {id: 5,name:"test"}
];

console.log(eqArrays(a1,a2,function(a,b) {
   return a.id === b.id;
}));