Home > Enterprise >  How to return a string (or break) from forEach loop when a condition is met
How to return a string (or break) from forEach loop when a condition is met

Time:12-03

I'm using Angular 14. I checked this and several other articles but none was useful at all. I've a piece of code in a ternary operator. The code is like this:

var finalValue = this.recordData.myArray.length === 0
            ? 'empty record'
            : this.recordData.myArray.forEach(
                (item: any) => {
                  if (item.stockKeepingStatus == 'A') {
                    this.thing = 'found';
                    // break; // syntax error
                    return this.thing;
                  } else {
                    this.thing = 'all are inactive';
                  }
                  return this.thing;
                }
              )

console.log(finalValue);

The logic is simple. If myArray is empty, then just say 'empty record'. Otherwise we will iterate through myArray array and check which item has stockKeepingStatus as active i.e. 'A'. The moment we find our first 'A' we will just break the loop and return 'found'. If none of thestockKeepingStatus was 'A' then we will just say 'all are inactive'. I'm getting finalValue undefined. Please point out my mistake.

CodePudding user response:

forEach() returns undefined.

You need to use every(), which checks whether all elements in the array pass the test implemented by the provided function.

var finalValue = this.recordData.myArray.length === 0 ?
  'empty record' :
  (this.recordData.myArray.every((item: any) => item.stockKeepingStatus == 'A') ?
    'found' :
    'all are inactive');

console.log(finalValue);

CodePudding user response:

You can use the break keyword within a forEach loop to return a string when a condition is met.

For example, let's say you want to iterate over an array of strings and return the first string that starts with the letter 'A'. You can use the following code to do this:

const strings = ["Alpha", "Bravo", "Charlie"];

let resultString = '';

strings.forEach(string => {
  if (string.startsWith('A')) {
    resultString = string;
    break;
  }
});

console.log(resultString); // 'Alpha'
  • Related