Friday, November 1, 2013

How to Check if one array is a subset of another array in Javascript?

I encountered this question in my code today. Although there are a lot of messy ways to do it which it will definitely lead to unmaintainable code, I guess I found the best answer.

Just to remind you, this solution will work if your supported browsers are of ECMA-262 standard. Therefore, for some of you guys out there, this might not work.

The key idea is to use every function in Javascript arrays. According MDN, "Tests whether all elements in the array pass the test implemented by the provided function."

Here is the signature of the method:

array.every(callback[, thisObject])

where callback is a function to test for each element, and thisObject refers to the object that we are testing array against (Remember that in Javascript, arrays are object. Right?)

Here is the snippet:

var arrayOfChildrenNames = ["Amir Rahnama", "Mahshid Rahnama"];
var arrayOfFamilyMemberNames = ["Davood Rahnama", "Maryam Toloo", "Amir Rahnama", "Mahshid Rahnama"];

var isarrayOfNamesSubsetOfFamily = arrayOfChildrenNames.every(function(val) { return arrayOfFamilyMemberNames.indexOf(val) >= 0; }));
console.log(isarrayOfNamesSubsetOfFamily); // true

If you are interested to know more about the function, check out MDN Documentation on Array every method

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. You've got an extra ")" on line 4.

    ReplyDelete
  3. That was a great message in my carrier, and It's wonderful commands like mind relaxes with understand words of knowledge by information's.
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete