jgg
jgg

Reputation: 1136

How to remove duplicate objects from java script array?

I have two arrays as shown below. I want to remove Array2 elements from Array1. How do I do that?(either in plain java script or using ExtJS)

var Array1 = [];

var Array2 = [];

Array1.push(['eth0'], ['eth1']);

Array2.push(['eth1']);

Upvotes: 0

Views: 727

Answers (3)

Tomalak
Tomalak

Reputation: 338228

function removeDupes(a1, a2) {
  var index = {}, result = [], i, l;
  for (i=0, l=a2.length; i<l; i++) {
    index['-' + a2[i]] = "";
  }
  for (i=0, l=a1.length; i<l; i++) {
    if (index['-' + a1[i]] !== "") result.push(a1[i]);
  }
  return result;
}
  • The index object is for speedy look-up of values so we can test their existence quickly.
  • The '-' + is to migrate the fact that values could be things like toString that also exist as object properties. When prefixed with a letter that regular JavaScript identifiers cannot start with, every value will be safe for use as an object key.

Example:

removeDupes([1,2,3,4], [2,4,5]);
// -> [1,3]

removeDupes([2,4,5], [1,2,3,4]);
// -> [5]

Upvotes: 1

carpamon
carpamon

Reputation: 6623

Check this link: http://www.developersnippets.com/2008/10/30/remove-duplicates-from-array-using-javascript/. Concat your arrays with concat() and call uniqueArr().

Upvotes: 0

rybosome
rybosome

Reputation: 5136

If you have the array filter function available to you, you can do something like the following:

var filteredArr = Array1.filter(function(val){
    return Array2.indexOf(val) != -1;
})

I think this will only be supported in newer browsers, though. It's an elegant way to handle the situation, so you may want to take a look at a library like UnderscoreJS which will include filtering, defaulting to the native implementation if available.

If using UnderscoreJS, the code would look very similar:

var filterdArr = _.filter(Array1, function(val) {return Array2.indexOf(val) != -1});

Upvotes: 1

Related Questions