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

Javascript: How to use map and filter between two array object

I am facing some issue on using .map and .filter where I am unable to get the object which is not similar in two objects.
What changes I need to do to get the uncommon object from arrayObjTwo.

code

const arrayObjOne = [{
          countryCode: "US",
          description: " Backyard of home",
          id: "1234",
          location: "US",
          name: "Backyard",
          }]
// Array Object 2
const arrayObjTwo =[
    { description: "Backyard of home", spaceName: "Backyard" },
    { description: "Frontyard of home", spaceName: "Frontyard"},
]
const object1Names = arrayObjOne.map(obj => obj.Name); // for caching the result
const results = arrayObjTwo.filter(name => !object1Names.includes(name));
console.log(results);

One compiler code: https://onecompiler.com/javascript/3xy92hpmp

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

expected result:

const arrayObjTwo =[
        { description: "Frontyard of home", spaceName: "Frontyard" }
    ]

Thanks..

>Solution :

Your filter for the result is wrong. You should be using the "object.spaceName" instead of just "name" as you’re looping through an array of objects and not just strings

// So this line:
const results = arrayObjTwo.filter(name => !object1Names.includes(name));

// Should be:
const results = arrayObjTwo.filter(object => !object1Names.includes(object.spaceName));

// And you have a typo:
const object1Names = arrayObjOne.map(obj => obj.Name);

// Should be like so as keys and properties are case-sensitive:
const object1Names = arrayObjOne.map(obj => obj.name);

So this should all be:

const arrayObjOne = [{
          countryCode: "US",
          description: " Backyard of home",
          id: "1234",
          location: "US",
          name: "Backyard",
          }]
// Array Object 2
const arrayObjTwo =[
    { description: "Backyard of home", spaceName: "Backyard" },
    { description: "Frontyard of home", spaceName: "Frontyard"},
]
const object1Names = arrayObjOne.map(obj => obj.name); // for caching the result
const results = arrayObjTwo.filter(object => !object1Names.includes(object.spaceName));
console.log(results);
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