Get exact objects with values defined in another array

Hi,
I wrote example snippet code. What I want to achieve is to find exact objects with the same IDs which are declared in another array with IDs.

const availablePeople = [{
    Name: "Test1",
    Age: '34',
    ID: 308
},
{
    Name: "Test2",
    Age: '35',
    ID: 368
},
{
    Name: "Test3",
    Age: '68',
    ID: 390
},
]

const IDsArray = [308, 368]

const testFn = () => {
    for (let i = 0, len = availablePeople.length; i < len; i++) {
        return availablePeople.filter(item => item.ID === IDsArray[i])
    }
}

console.log(testFn()); // Show object with the same IDs
// Now result:
// [ { Name: 'Test1', Age: '34', ID: 308 } ]
// What I want to achieve :
// [ { Name: 'Test1', Age: '34', ID: 308 }, { Name: 'Test2', Age: '34', ID: 368 } ]

Thank you for your time.
If you know any modern solution, share with me.

This sounds like just the job for filter to do by itself, without other loops getting in the way.

const chosenPeople = availablePeople.filter(function (person) {
	return IDsArray.includes(person.ID);
});
1 Like

Thank you a lot.
I have just written another solution:

const testFn = () =>
    IDsArray.map(el => availablePeople.find(o => o.ID === el));

another with filter():

 IDsArray.map(el => availablePeople.filter(o => o.ID === el));

Reformatting my earlier code to the style that you use, we get:

const testFn = () => 
    availablePeople.filter(o => IDsArray.includes(o.ID));
1 Like

Yes, thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.