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

1

5 Answers 5

8

Try:

var diff = $(array1).not(array2).get();
2
  • When it try this output is '[1, 2, 6, diff: function]' How to remove that 'diff: function' from that?
    – Okky
    Sep 25, 2013 at 7:46
  • 2
    Looks okay on fiddle, jsfiddle.net/nKNdA , try your data here and update, send the link please.
    – Kamil
    Sep 25, 2013 at 7: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!

1

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

1

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

0

Underscore.js library helps: Hers is what you need

_.difference(array1, array2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.