0

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']);
jgg
  • 1,136
  • 4
  • 22
  • 46
  • possible duplicate of http://stackoverflow.com/questions/1187518/javascript-array-difference ? – Fabrizio Calderan Jan 19 '12 at 19:32
  • 2
    Do you want to remove the values completely, or just the duplicate values? – Justin Lucas Jan 19 '12 at 19:33
  • @Michael Dillon Its not exact duplicate. Maybe ExtJS has some synonym to [underscore](http://documentcloud.github.com/underscore/)'s `_.uniq()` ? – c69 Jan 19 '12 at 19:34
  • Are you sure you want an array of arrays, not of strings? `Array1` looks like `[['eth0'], ['eth1']]`. You sure you want that, compared to `['eth0', 'eth1']`? – gen_Eric Jan 19 '12 at 19:38

3 Answers3

1
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]
Tomalak
  • 332,285
  • 67
  • 532
  • 628
1

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});
rybosome
  • 5,046
  • 7
  • 44
  • 64
0

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

carpamon
  • 6,515
  • 3
  • 38
  • 51
  • That link you provided gives a solution to remove duplicates from just one array, and not two as asked. – Nobita Jan 19 '12 at 19:33