12

Put simply, I want to subtract one array from another.

The arrays are arrays of objects. I understand I can cycle through one array and on each item, comparing values in the other array, but that just seems a little messy.

Thanks for the help, hopefully this question isnt too basic, I have tried googling it with no luck :(

EDIT:

The Objects in the Arrays I wish to remove will have identical values but are NOT the same object (thanks @patrick dw). I am looking to completely remove the subset from the initial array.

3
  • 1
    Do the arrays hold references to the same objects, or are they references to unique objects with potentially the same data? {a:1} != {a:1} yet var a = b = {a:1}; a == b Commented Jan 6, 2011 at 22:59
  • I'm not quite sure this question is specific enough. In what way do you want to subtract these arrays? Are you looking to subtract them such that the nth element of the new array is the nth element of the first minus the nth element of the second? Or is your intent rather to do some sort of "set difference" on these arrays? Commented Jan 6, 2011 at 23:02
  • thanks for the comments. I have edited the question to better explain the problem. Commented Jan 7, 2011 at 0:43

4 Answers 4

33

This answer is copied from https://stackoverflow.com/a/53092728/7173655, extended with a comment and a solution with objects.

The code filters array A. All values included in B are removed from A.

const A = [1, 4, 3, 2]
const B = [0, 2, 1, 2]
console.log(A.filter(n => !B.includes(n)))

The same with objects:

const A = [{id:1}, {id:4}, {id:3}, {id:2}]
const B = [{id:0}, {id:2}, {id:1}, {id:2}]
console.log(A.filter(a => !B.map(b=>b.id).includes(a.id)))

Sign up to request clarification or add additional context in comments.

Comments

3

http://phpjs.org/functions/index

There is no built-in method to do this in JavaScript. If you look at this site there are a lot of functions for arrays with similar syntax to PHP.

2 Comments

link not found.
@weltschmerz here's a copy from the wayback machine web.archive.org/web/20130713181607/http://phpjs.org/functions
2

http://www.jslab.dk/library/Array

This site has some js functions on "sets"

I think you need the diff function.

Comments

1

It should remove all values from list a, which are present in list b keeping their order.

  let a = [0, 2, 5, 6, 1];
  let b = [2, 6, 2, 5, 0];

  function arrayDiff() {
    for (i of b) {
      for (j of a) {
        if (i === j) {
          a.splice(a.indexOf(j), 1);
        }
      }
    }
    return a;
  }

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.