Luxx
Luxx

Reputation: 3

Push all the key values from an array into a new array, so long as a different key's values (in the same object) meet a certain condition

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

Answers (3)

alexlexis
alexlexis

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

Seth Flowers
Seth Flowers

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

  • Array.prototype.filter The filter() method creates a new array with all elements that pass the test implemented by the provided function.
  • Array.prototype.map The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Upvotes: 2

schu34
schu34

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

Related Questions