Showing posts with label Data Structure. Show all posts
Showing posts with label Data Structure. Show all posts

Monday, December 23, 2013

Remove duplicates in an array in Javascript

If you follow this approach, you need to create another array and if you have performance limitations you need to consider that.

This algorithm will be o(n)complexity in which n is the length.

With jQuery:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 $.each(array, function(i, element) { 
   if ($.inArray(element, newArray) === -1) {
       newArray.push(region); 
   }
 });

 console.log(newArray); // ["amir", "rahnama", 1];

Vanila Javascript:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 array.forEach(function(i, element) { 
   if (newArray.indexOf(element) === -1) { 
      newArray.push(region); 
   }
 });
 console.log(newArray); // ["amir", "rahnama", 1];

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