0

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 .

2 Answers 2

1

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:

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.