aszet
aszet

Reputation: 93

forEach is returning undefined

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

Answers (4)

Mamun
Mamun

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

Nipun Jain
Nipun Jain

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

Tugrul Emre Atalay
Tugrul Emre Atalay

Reputation: 938

forEach has no return value. You should use map function to change the element's types.

Upvotes: 2

tadman
tadman

Reputation: 211740

If you want to transform the array, you want map:

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: 1

Related Questions