Reputation: 3
The best way to describe the solution I'm looking for is an elegant way to make a function for this:
function getNamesOfLegalDrivers(people) {
}
const examplePeopleArray = [
{ name: 'John', age: 14 },
{ name: 'Joey', age: 16 },
{ name: 'Jane', age: 18 }
];
console.log(getNamesOfLegalDrivers(examplePeopleArray), '<-- should print all names over 16, and thus be ["Joey", "Jane"]');
Upvotes: 0
Views: 744
Reputation: 11
You could do something like this:
function getNamesOfLegalDrivers(people)
{
var legalDrivers = [];
for (var i in people) {
if(people[i].age >= 16){
legalDrivers.push(people[i].name);
}
}
return legalDrivers;
}
const examplePeopleArray = [
{ name: 'John', age: 14 },
{ name: 'Joey', age: 16 },
{ name: 'Jane', age: 18 }
];
console.log(getNamesOfLegalDrivers(examplePeopleArray));
Upvotes: 1
Reputation: 9180
You are looking for functions on the Array
prototype, like filter
and map
.
Javascript
function getNamesOfLegalDrivers(people) {
return people
.filter(function(person) { return person.age >= 16; })
.map(function(person) { return person.name; });
}
Documentation from MDN
filter()
method creates a new array with all elements that pass the test implemented by the provided function.map()
method creates a new array with the results of calling a provided function on every element in the calling array.Upvotes: 2
Reputation: 985
function getNamesOfLegalDrivers(people) {
return people
.filter(person=>person.age >= 16) //returns array of all person objects over 16
.map(person=>person.name)//returns name of all people in the filtered array
}
Upvotes: 1