Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript arrays of Objects; Subtract one from another

Tags:

javascript

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.

like image 530
neolaser Avatar asked Jan 06 '11 22:01

neolaser


2 Answers

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)))
like image 192
Adrian Dymorz Avatar answered Sep 18 '22 04:09

Adrian Dymorz


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.

like image 28
sissonb Avatar answered Sep 19 '22 04:09

sissonb