var people = [
{name: 'John', id: [34, 44, 77]},
{name: 'Jose', id: [43, 54, 65]},
{name: 'Hanna', id: [56, 34, 98]}
];
var peopleFinder = people.filter(function(b){
return b.id === 56;
}).map(function(n2){
return n2.name;
})
console.log(peopleFinder);
How to print an name from an array of objects, by a given ID. This has to be solve without using any type of loops. Just array methods are allow to be use: .filter(), .map(), .reduce() and .find().
5
Answers
However, since the id property in each object is an array, you need to use the
.includes()
method to check if the given ID exists within the array.Please check below code and try, i have made some changes:
In this code, the
filter()
method is used to find the objects that have the ID 56 in their id array. Theincludes()
method is used to perform the check. Then, themap()
method is used to extract the name property from the filtered objects.Hope this will help !
You’re almost there. Just make sure you check if the
id
arrayincludes
the id you’re looking for and don’t compare by value:Well, first we need to filter out the ones that dont have the id we are searching for. For that we user
filter()
.In more detail, what the filter function does is filters the array to only include the items that match out criteria.
After that we have to map our user’s name, so we user the
map()
function.Then by putting them both together we should get the name of the person with the Id we need.
An
Array::reduce()
compact version:And a benchmark:
Just for fun, don’t try to reproduce at home, a regex version 🙂
You can use
Array#find
method as follows: