Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Pushing an object to an array from a foreach

I want to extract a collection of objects from an array based on their ID. I am using vanilla Javascript.

contacts = [
    {ID: 1, firstName: "Aaron", lastName: "Smith"},
    {ID: 2, firstName: "Ben", lastName: "Smith"},
    {ID: 3, firstName: "Conrad", lastName: "Smith"}
];
filteredContactIds = [1, 3];
filteredContacts = [];

filteredContactIds.forEach(function (filteredId) {
    filteredContacts.push(
        contacts.forEach(function (contact) {
            if (contact.ID == filteredId) {
                return contact;
            }
        })
    )
});

Contacts and filteredContactIds are simplified, in my code both arrays are both populated correctly. The problem is, the filteredContacts array is only receiving the ID property of each contact object, I want to insert the whole object.

I have exhausted my limited understanding. Can anyone point out the problem?

like image 836
Ben E. Avatar asked Mar 14 '26 20:03

Ben E.


1 Answers

The problem with your approach is that Array#forEach doesn't return a value. It just performs some operation(s) on each item in an array. This means undefined is being pushed to filteredContacts. You could use contacts.filter but you can remove the inner loop.

Using Array#filter and an array containment check:

const contacts = [
    {ID: 1, firstName: "Aaron", lastName: "Smith"},
    {ID: 2, firstName: "Ben", lastName: "Smith"},
    {ID: 3, firstName: "Conrad", lastName: "Smith"}
];
const filteredContactIds = [1, 3];
const filteredContacts = contacts.filter(({ ID }) => filteredContactIds.includes(ID));
console.log(filteredContacts);

Instead of having to have two loops, one single run through the contacts array will work. This iterates through the array and checks whether the current contact's ID is inside the filteredContactIds array, removing another loop. Here's a desugared version for ES5 and below:

var contacts = [
    {ID: 1, firstName: "Aaron", lastName: "Smith"},
    {ID: 2, firstName: "Ben", lastName: "Smith"},
    {ID: 3, firstName: "Conrad", lastName: "Smith"}
];
var filteredContactIds = [1, 3];
var filteredContacts = contacts.filter(function(contact) {
  return filteredContactIds.indexOf(contact.ID) > -1;
});
console.log(filteredContacts);

Instead of Array#includes, it uses Array#indexOf, and does not use object destructuring nor arrow functions nor const.

like image 149
Andrew Li Avatar answered Mar 17 '26 08:03

Andrew Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!