Higher-order Function Exercise
We will use the given array helpers to transform the given for
loops away from being for
loops.
Here is some data you can use, feel free to add more car objects to it:
const cars = [
{
make: "ford",
model: "E150",
year: 2000
},
{
make: "chevy",
model: "malibu",
year: 2017
},
{
make: "chevy",
model: "malibu",
year: 2003
},
{
make: "ford",
model: "E150",
year: 1999
},
{
make: "chevy",
model: "sedan",
year: 2009
},
]
Use .forEach()
to replace the following for
loop.
for (let i = 0; i < cars.length; i++) {
console.log(`${cars[i].length} goes vroom`);
}
Use .map()
to replace the following for
loop.
var angryCars = [];
for (let i = 0; i < cars.length; i++) {
angryCars.push(cars[i].make.toUpperCase());
}
Use .filter()
to replace the following for
loop.
var newCars = [];
for (let i = 0; i < cars.length; i++) {
if (cars[i].year > 2005){
newCars.push(cars[i]);
}
}
Use .find()
to replace the following for
loop.
for (let i = 0; i < cars.length; i++) {
if (cars[i].model === "E150"){
let coolVan = cars[i];
break;
}
}
Use .some()
to replace the following for
loop.
for (let i = 0; i < cars.length; i++) {
if (cars[i].model === "E150"){
console.log("It is true that there is one or more E150s");
break;
}
}
Use .every()
to replace the following for
loop.
for (let i = 0; i < cars.length; i++) {
if (cars[i].model != "E150"){
console.log("It is false that every car is an E150");
break;
}
}
Use .reduce()
to replace the following for
loop and carTotals definition.
var numberOfFords = 0;
var numberOfChevys = 0;
for (let i = 0; i < cars.length; i++) {
if (cars[i].make === "ford"){
numberOfFords ++;
}
if (cars[i].make === "chevy"){
numberOfchevys ++;
}
}
let carTotals = { numberOfFords: numberOfFords, numberOfChevys: numberOfChevys }