0

I have two arrays:

var firstArr = [1,2,3,4,5];
var secondArr = [2,3];

How can I get an array like this:

[1,4,5]

I would like to use a solution that could be used when elements of the array are objects with multiple properties.

3
  • If you can use underscore: underscorejs.org/#uniq Commented Jun 28, 2015 at 15:16
  • possible duplicate of Comparing two arrays in Javascript Commented Jun 28, 2015 at 15:16
  • @epascarello This question is not about removing duplicates... Commented Jun 28, 2015 at 15:20

2 Answers 2

2

Use filter:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

For example:

firstArr.filter(function(item){ 
    return secondArr.indexOf(item) === -1; 
});
Sign up to request clarification or add additional context in comments.

1 Comment

For OP's second request (array elements are objects), it should be noted that this will only work if the same object is present in both arrays, and not just a copy of that object.
0

You can use this Function to remove items.

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.