0

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"}
]
Nipun Jain
  • 999
  • 6
  • 13
aszet
  • 83
  • 7

4 Answers4

4

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";
    }
  });
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • What about breaking the loop when the first `if` is true? – aszet Jan 19 '20 at 05:35
  • 1
    @aszet, you can not even brake the loop, they are bound to execute for all the elements in the array. To break the loop you have to use simple *for* loop. – Mamun Jan 19 '20 at 05:38
  • @aszet If you want some, use `.some()`, if you want all use `.every()`. See [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) for examples. – some Jan 19 '20 at 05:45
2

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

Tugrul Emre Atalay
  • 918
  • 1
  • 9
  • 28
1

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";
    }
  });
}
tadman
  • 208,517
  • 23
  • 234
  • 262
  • You're going to have to be more specific about what the issue is, then. What output *do* you want? – tadman Jan 19 '20 at 05:31
0

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
    }
Nipun Jain
  • 999
  • 6
  • 13