wilded
4/3/2019 - 8:18 AM

Filter in an Array of Objects in Javascript and Print Results (With Arrow Functions)

<!DOCTYPE html>
<html>
<body>
<p>Click the button to check get the value of the first element in the array that has a value of 18 or more.</p>
<button onclick="returnAdults()">Try it</button>
<p id="demo"></p>
<script>
// We initialize our variable demo as an object
let demo = document.getElementById("demo");

// We initialize our array of objects
const peopleList = [
  {
  name: "Joe",
  age: 3
  }, 
  {
  name: "Sara",
  age: 10
  }, 
  {
  name: "Luis",
  age: 18
  }, 
  {
  name: "Franzi",
  age: 20
  }
];
// people could be any value, in this case is passed as an array
const adultsList = peopleList.filter((people)=>{
  return people.age >= 10;
})
// This function appends in variable demo the values of the array of objects adultList
const printAdultList = (person, index) => demo.innerHTML +=  "index[" + index + "]: " + person.name + " " + person.age + "<br>";
// This function uses forEach on the adultList array and calls another function (printAdulrList) to format the result
const returnAdults = () => adultsList.forEach(printAdultList);
</script>