Reputation: 93
I want my foreach() to loop through an array of maps and check if the type value matches. If not return the else statement.
Function
function checkCars(carData) {
const cars = carData.models;
models.forEach(model => {
if (model.type === 'Toyota' || model.type === 'Hyundai') {
return "Type A";
} else {
return "Type B";
}
});
}
Database
"models": [
{type: "Toyota"}
{type: "Hyundai"}
{type: "Audi"}
{type: "VW"}
]
Upvotes: 0
Views: 102
Reputation: 68933
The return value of Array.prototype.forEach() is undefined
, you can not return anything explicitly from forEach()
.
You can try with Array.prototype.map() instead:
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
function checkCars(carData) {
const cars = carData.models;
return models.map(model => {
if (model.type === 'Toyota' || model.type === 'Hyundai') {
return "Type A";
} else {
return "Type B";
}
});
}
Upvotes: 4
Reputation: 1014
You can use something like this:
function checkCars(carData) {
const cars = carData.models;
let type = "Type A"
models.forEach(model => {
if (model.type !== 'Toyota' && model.type !== 'Hyundai') {
type = "Type B";
}
});
return type
}
Upvotes: 0
Reputation: 938
forEach has no return value. You should use map function to change the element's types.
Upvotes: 2