2

What is the best way to check whether elements from one array are present in another array using JavaScript?

I come up with two of the following methods (but neither of them do I like very much).

Method1

for(let i = 0; i < arr1.length; ++i) {
    for(let j = 0; j < arr2.length; ++j) {
        if(arr1[i] === arr2[j]) {
            arr1[i].isPresentInArr2 = true;
            break;
        }
    }
}

Method2

const idToObj = {};
for(let i = 0; i < arr2.length; ++i) {
    nameToObj[arr2[i].Id] = arr2[i];
}
for(let i = 0; i < arr1.length; ++i) {
    if(nameToObj[arr1[i].Id]) {
        nameToObj[arr1[i].Id].isPresentInArr2 = true;
    }
}

Here I am assuming that I have two arrays of objects: arr1 and arr2. Those objects have a unique Id property each. And I am to check whether every object in arr1 is present in arr2.

I suppose the second method would be more efficient. Hope for interesting suggestions.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
yourbuddy
  • 73
  • 1
  • 6
  • if you have array of objects as you said, doing a comparism at `arr1[n] === arr2[n]` will evaluate to fasle because in javascript `{} === {}` always evaluate to false, especially if does objects in the array are not referencing each other. what do you actually need, to compare the array elements which are objects or to compare values in that object if it is present in the other array of objects value – 0.sh Nov 24 '18 at 17:44
  • Possible duplicate of [Check if an array contains any element of another array in JavaScript](https://stackoverflow.com/questions/16312528/check-if-an-array-contains-any-element-of-another-array-in-javascript) – Heretic Monkey Nov 24 '18 at 17:49

4 Answers4

0

in terms of Algorithm Complexity wise , It's like trade-offs . First One - Space time Complexity - 0, Run time complexity - 0(n2)

Second One - Space time Complexity - o(n), Run time complexity - 0(n)

If it's performance focussed , go for second one .

In terms of js way , you have many ways . Read about includes() and indexOf() inbuilt method in javascript to avoid writing a loop . Also make use of javascript map function . You could also uses underscore.js

Ref Check if an array contains any element of another array in JavaScript for more details .

melvil james
  • 592
  • 7
  • 18
0

You could get a list of Ids, then sort the id's and compare the two array lists of Ids using JSON.stringify

// Test arrays to work with
const array1 = [{Id:10},{Id:11},{Id:13},{Id:12}]
const array2 = [{Id:10},{Id:11},{Id:12},{Id:13}]
const array3 = [{Id:10},{Id:11},{Id:12}]

function test(arr1, arr2) {
  // Map of each array [0, 1, 2, etc...]
  let map1 = arr1.map(i => i.Id)
  let map2 = arr2.map(i => i.Id)

  // Sort each array from lowest to highest
  // Note: Some kind of sort is required if we are going to compare JSON values
  map1.sort()
  map2.sort()

  // Test the mapped arrays against each other
  return JSON.stringify(map1) === JSON.stringify(map2)
}

console.log(test(array1, array2))
console.log(test(array1, array3))
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

You could sort the arrays, then check if they are equal to one another:

var array1 = [4, 304, 2032], // Some random array
  array2 = [4, 2032, 304];

function areEqual(array1, array2) {
  if (array1.sort().toString() == array2.sort().toString()) {
    // They're equal!
    document.getElementById("isEqual").innerHTML = ("Arrays are equal");
    return true;
  } else {
    // They're not equal.
    document.getElementById("isEqual").innerHTML = ("Arrays aren't equal");
    return false;
  }
}
areEqual(array1, array2);
<!DOCTYPE html>
<html>

<body>
  <p id="isEqual"></p>
</body>

</html>
Sarah
  • 460
  • 4
  • 9
0

map over the arrays of objects to produce arrays of ids, then use every and includes to check the elements in one array against the elements of the other: ids1.every(el => ids2.includes(el)).

Here's a working example:

const arr1 = [{ id: 0 }, { id: 1 }, { id: 2 }];
const arr2 = [{ id: 0 }, { id: 1 }, { id: 2 }];
const arr3 = [{ id: 14 }, { id: 1 }, { id: 2 }];

const getIds = (arr) => arr.map(el => el.id)

function check(arr1, arr2) {
  const ids1 = getIds(arr1);
  const ids2 = getIds(arr2);
  return ids1.every(el => ids2.includes(el));
}

console.log(check(arr1, arr2));
console.log(check(arr1, arr3));
Andy
  • 61,948
  • 13
  • 68
  • 95