5

I have two arrays

var array1 = new Array ["a", "b", "c", "d", "e"];
var array2 = new Array ["a", "c", "d"];

I want to remove elements of array2 from array1

Result ["b", "e"]

Is there anything like

array1 = array1.remove(array2)

Note I'm using jquery-1.9.1

Okky
  • 10,338
  • 15
  • 75
  • 122
  • possible duplicate of [JavaScript array difference](http://stackoverflow.com/questions/1187518/javascript-array-difference) – Itay Sep 25 '13 at 07:31

5 Answers5

8

Try:

var diff = $(array1).not(array2).get();
Kamil
  • 782
  • 1
  • 6
  • 22
  • When it try this output is '[1, 2, 6, diff: function]' How to remove that 'diff: function' from that? – Okky Sep 25 '13 at 07:46
  • 2
    Looks okay on fiddle, http://jsfiddle.net/nKNdA/ , try your data here and update, send the link please. – Kamil Sep 25 '13 at 07:54
2
function difference(source, toRemove) {
    return source.filter(function(value){
        return toRemove.indexOf(value) == -1;
    });
}

NOTE: Array.prototype.indexOf and Array.prototype.filter are not available before IE9!

Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
1

Although lot of ways to achieve it through native java script but i recommend to see Underscore library

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
1

Underscore JS is what you need. This library has lots of useful array manipulation functions. Underscore JS

Jabran Saeed
  • 5,760
  • 3
  • 21
  • 37
0

Underscore.js library helps: Hers is what you need

_.difference(array1, array2);
slfan
  • 8,950
  • 115
  • 65
  • 78
ars
  • 1