简体   繁体   中英

How to return specific values from an array with objects inside in a new array which must pass a test?

Hello I am try to get the solution but dont find the right answer on my own research and hope somebody can help me with my problem. The task required that I must write a function which returns every persons name which is 16 or older in a new array. The goal is to write a function which returns in my example: ['Jane', 'Jack']


function onlyAdult(obj) {

}


const examplePeopleArray = [
  { name: 'John', age: 15 },
  { name: 'Jane', age: 16 },
  { name: 'Jack', age: 17 }
];

console.log(onlyAdult(examplePeopleArray));


I tried to manage the task with a for loop which loop through the array and connected a if statement but this way it doesnt worked. After this i tried to find the right methods for my task with every(),filter(), forEach(), map(), some() but none of these actually worked for my task .

function onlyAdult(obj) {
for (i = 0; i < obj.length; i++) {
  if (obj[0].age >= 16) {
    return obj[0].age;
  } else if (obj[1].age >= 16) {
    return obj[1].age;
  } else if (obj[2].age >= 16) {
    return obj[2].age;
  }
}
}

I know my code is wrong and also the way I tried to solved it, I would be very grateful when someone could help me .

You can filter the array first using .filter() and then use .map() to get the desired property values only.

 const data = [ { name: 'John', age: 15 }, { name: 'Jane', age: 16 }, { name: 'Jack', age: 17 } ]; const result = data.filter(({ age }) => age >= 16).map(({ name }) => name); console.log(result); 

References:

 const examplePeopleArray = [ { name: 'John', age: 15 }, { name: 'Jane', age: 16 }, { name: 'Jack', age: 17 } ]; const result = examplePeopleArray.reduce((arr, el) => { if (el.age >= 16) arr.push(el.name) return arr }, []) 

For this given task reduce will be enough. Here we reduce input array to an array of filtered string values based on age comparison. If age is under 16 we just do not push anything and skip to the next element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM