0

I have an array of objects that looks like this:

contacts: [
    {
      id: 1,
      name: "John Doe",
      email: "[email protected]",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "Karen Williams",
      email: "[email protected]",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "Henry Johnson",
      email: "[email protected]",
      phone: "333-333-333",
    },
  ]

I want to loop through them and if one of their ID's matches the ID I am looking for then I need that return and assigned to another variable. This is what I have so far but it tells me the selectedContact is undefined.

function getSingleContactFromId(contacts, id) {
  contacts.forEach((contact) => {
    console.log(contact);
    if (contact.id == id) {
      console.log(contact);
      return { contact };
    }
  });
}

const selectedContact = getSingleContactFromId(contacts, id);
      console.log(selectedContact);


1
  • try using Array#find Commented Jun 3, 2020 at 18:06

4 Answers 4

2

You are returning value from inside the interatee function of the forEach. What you can do is to add a variable where you can store the selected contact and return it after exiting the loop.

function getSingleContactFromId(contacts, id) {
    let selectedContact;
      contacts.forEach((contact) => {
        console.log(contact);
        if (contact.id == id) {
          console.log(contact);
          selectedContact = { contact };
          return false;
        }
      });
    return selectedContact;
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's because forEach returns undefined, returning anything inside it does nothing. You need to use something like map, filter, or a normal for loop and break when you hit a matching id.

Something like this would work:

let foundContact = null;
for (let i = 0; i < contacts.length; i++) {
 if (contacts[i].id === id) {
   foundContact = contacts[i];
   break;
 }
}

return foundContact;

You can do the same with using filter:

return contacts.filter(contact => {
  return contact.id === id;
})

Comments

0
function getSingleContactFromId(contacts, id) {
  let c = null;
  contacts.forEach((contact) => {
    if (contact.id === id) {
      c = contact;
      return false;
    }
  });
  return c;
}

return false is the circuit breaker for forEach as break doesn't work.

Comments

0

I realized this was a rookie mistake, but I decided to go with this:

var contact;
  console.log("get single contact");
  for (var i = 0; i < state.contacts.length; i++) {
    contact = state.contacts[i];
    if (contact.id == id) {
      return contact;
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.