Tips for looping through an array to filter out contacts that do not contain a specific item

I've been grappling with this task for more than sixty minutes and am at a loss on what to incorporate... Instructions:

-Filtering Data.. The search functionality of the application empowers users to filter contacts in various manners. The interviewer has requested that you exclude those who do not possess an Instagram account.

Utilize the given contacts array to store the contacts without an Instagram account in a variable named 'noInstagram.' Avoid simply hard-coding the solution into the variable, instead programmatically filter out the contacts from the array.

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.instagram){
console.log(contact)
}
})

Answer №1

Give this a try:

let contactsWithoutInstagram = contacts.filter(contact => !contact.social_media.instagram);
console.log(contactsWithoutInstagram);

The filter function requires a callback function as an argument and outputs an array containing the elements that meet the specified condition.

This filtered array will only include elements from the original array that satisfy the criteria in the callback function.

Answer №2

const noInstagramContacts = contacts.filter(contact => contact.social_media.instagram === undefined);

Alternatively,

const noInstagramContacts = contacts.filter(contact => !contact.social_media.hasOwnProperty("instagram"));

Answer №3

Heading in the right direction with a filter, check out the Array.filter documentation

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

Remember, you need to return either true or false within the filter function to properly filter the current object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The proper way to insert data in JavaScript and PHP

Hello. I have a new function to add a row in my form. However, I recently added a second input field and I am unsure of how to correctly insert it. Below is my JavaScript code: <script type="text/javascript" src="jquery.js"></script> <scri ...

Is it possible to use a full-width material-ui Button inside a Badge component?

Within a grid, I had initially used fullWidth on a Button to make it expand and fill the container. Everything was functioning correctly until I enclosed the Button in a Badge element. Now, the fullWidth property is not being applied, and the button rever ...

Asynchronously loading images within a div that has overflow: scroll, as they come into view

The setup I have for displaying my content looks like this: <div id="content" style="overflow:scroll;height:500px; width: 500px;"> <div style="width:500px;height:100px;> <img src='http://graph.facebook.com/user1/picture?width= ...

What is the best way to code a JavaScript function that changes the labels on a mat-slider when using a range

As a newcomer, I am currently working with a mat-slider and trying to modify the label based on the range selected. However, I'm unsure how to write JavaScript code for different labels. Can anyone provide me with assistance? Here is the mat-slider th ...

Is it possible to implement a modal within my API services?

Hello, I am in need of assistance. I am looking to display a modal every time my API returns an error. Can someone please help me figure out how to achieve this? I am currently using React hooks. const restService = (path, responseType = 'json') ...

What is the best way to guide users to different pages on the website without disrupting the socket connection?

I am looking to create a user-friendly web application utilizing socket.io and express. This website will consist of two main pages: the "Rooms" page and the individual "Room" page. The "Rooms" page allows users to input their name, create a new room, or j ...

What is the best way to ensure data validation occurs only when a button is clicked

In my project, I am faced with the challenge of validating inputs only after a submit button is clicked. However, I have noticed that the required rule is being activated after losing focus. This issue arises while using VeeValidate in Vue.js. Here is the ...

Navigating a 'f0_' attribute

I wrote a SQL query in BigQuery using a common table expression to generate a list of dates within a specific range: WITH calendar AS( SELECT * FROM UNNEST(GENERATE_DATE_ARRAY('2020-01-01', CURRENT_DATE(), INTERVAL 1 DAY)) ) W ...

Refreshing JSP Pages with Updated ActionBean Variables in Stripes Framework

Having recently started working with Stripes, I am trying to customize the number of records displayed on a paginated table based on the dropdown selection ("show ## records per page"). However, I am struggling to set the value of the "recordsPerPage" vari ...

Trouble with binding to an array inside a Vue component instance

Trying to grasp the concepts of vue.js, but struggling with a crucial element. The goal is to create an accordion functionality for multiple boxes (only one box displayed at a time; opening a new box closes any previously open ones). Here's the curre ...

Using an arrow function to assign a value to a variable

I have a quick question as I'm still learning arrow functions. I understand that they implicitly return, and we can use implicit returns with expressions. However, my question is about the following scenario: $scope.setEdit = () => { $scope.edit = ...

Assigning nested JSON values using Jquery

My JSON data structure is as follows: { "Market": 0, "Marketer": null, "Notes": null, "SalesChannel": null, "ServiceLocations": [ { "ExtensionData": null, "AdminFee": 0, "CommodityType": 0, ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

Discrepancies in rounding calculations between three.js on Chrome and Firefox

In my three JS scene, I have a plane positioned and rotated in a certain way. When I send a raycast towards this plane and project an object onto it, everything works perfectly fine in chromium but gets turned upside down in firefox. This discrepancy is c ...

Combining two unchangeable objects in JavaScript: A guide

Currently, I'm working on a project using React and Formik. In my validation file, I have exported two validation schema named as `facValidation` and `insValidation`. Here is the content of my `validation.js` file: export const facValidation = Yup.o ...

Is it possible to automatically update a select list with variable values based on the selection of another select option

Within my PHP code, I have defined an array called $programDates_items that contains various school program values, each with multiple dates assigned to them. Additionally, I have a form with a select input labeled "program of interest," which presents dif ...

Using CSS to create a zoom effect with absolute positioning

I am attempting to implement an interesting effect on my website where clicking a thumbnail causes a full-size div to "zoom in" from the thumbnail. My initial strategy involved using CSS and jQuery, setting the full-size div to position:absolute with top a ...

Express app unable to receive data from Ajax request

I'm currently in the process of developing an application with React and Express. The issue I'm facing is that when I make an Ajax request from a React component to a specific Express route, the data doesn't seem to be reaching the route han ...

Display a still image in cases where the browser does not support 3D images

I need to display a 3D image in my HTML page if the browser supports canvas, otherwise I want to show a static image. The image should be loaded dynamically when the page loads. <!DOCTYPE html> <html class="no-js" lang="en"> <head> ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...