Home > Back-end >  How to iterate through an array and have it return only the contacts missing a certain object
How to iterate through an array and have it return only the contacts missing a certain object

Time:07-18

I've been working on this for over an hour and have no clue what to include... directions:

-Filtering Data.. The application's search feature allows users to filter contacts in various ways. The interviewer would like you to filter out those who do not have an Instagram account.

Using the given contacts array, save the contacts who do not have an Instagram account to a variable called 'noInstagram.' Don't just hard-code the answer into the variable but rather filter the contacts out of the array programmatically.

let contacts = [
    {
        name: "Jane Doe",
        age: 21,
        social_media: {
            instagram: "jane.doe",
            twitter: "jane_doe"
        }
    },
    {
        name: "John Doe",
        age: 21,
        social_media: {
            instagram: "john.doe",
            twitter: "john_doe"
        }
    },
    {
        name: "Mary Deer",
        age: 21,
        social_media: {
            twitter: "mary_deer"
        }
    },
    {
        name: "Gary Deer",
        age: 21,
        social_media: {
            twitter: "gary_deer"
        }
    }
]

How Im starting off.  

let noInstagram = contacts.filter((contact) => {
if ( contact.social_media. ????){
console.log(contact)
}
})

CodePudding user response:

Try this :

let noInstagram = contacts.filter(c => !c.social_media.instagram);
console.log(noInstagram);

The filter method take a callback function as parameter and return an array.

This array is filled with all the element of the inital array that return true after passing throw the callback function.

CodePudding user response:

let noInstagram = contacts.filter(contact => contact.social_media.instagram === undefined);

or

let noInstagram = contacts.filter(contact => !contact.social_media.hasOwnProperty("instagram"));

CodePudding user response:

You are going in a good direcction with a filter, please visit Array.filter docs

let noInstagram = contacts.filter((contact) => {
    //Return true if instagram is not found
    return !contact.social_media.instagram
})

As you see, you must return true or false inside the filter to be able to filter or not the current object.

  • Related