Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter object by value

Let’s say I have:

let object1 = [{id: 15, name: name1}, {id: 0, name: name2}, {id: 98, name: name3}];
let object2 = [{id: 2, action: action}, {id: 88, action: action}, {id: 0, action: action}];

ID numbers don’t match on purpose.
How could I get name values from object1 whose ID’s don’t appear in object2?

Edit: I’ve tried to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let results;
for (let i = 0; i < object1.length; i++) {
         results = object2.filter(element => { return element.id != object1[i].id } );
    }

Also tried to get it working with .map(), but with no luck.

>Solution :

You could use filter() on one of the arrays and find() to filter out the objects from that array with ids that don’t occur in the other array.

let oArr1 = [{id: 15, name: "name1"}, {id: 0, name: "name2"}, {id: 98, name: "name3"}];
let oArr2 = [{id: 2, action: "action"}, {id: 88, action: "action"}, {id: 0, action: "action"}];

const result = oArr1.filter(x => !oArr2.find(y => y.id === x.id));

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading