Abort the forEach loop (javascript)


massiv.forEach(function(item, i) {
  if (item == "1") {
    console.log(i);
    return false;
  }
});

There is an array with values.

Inside the loop, there is a search condition for the array value.

Task: stop further iteration of the loop at the first found value.

Thanks for the help.

Solution: (thanks to Lieutenant Jim Dangle)

[1, 2, 3, 4, 3].some(function(el,i) {

         if (el == 3) {  
         console.log(i);
         return el;
         }

    }); 

4 answers

The forEach method does not allow you to abort the collection traversal.

If you need to check for a specific element that meets the condition, it is better to use the method some

var massiv = ['2', '1', '3'];

console.log(massiv.some(function(item) {
  console.log('some', item);
  return (item == "1");
}));

If the objects are fully checked, you can use the indexOf{[9 method]}

var massiv = ['2', '1', '3'];

console.log(massiv.indexOf("1"));

If you need to find the index of an element that meets the condition, then the method is suitable findIndex

var massiv = ['2', '1', '3'];

console.log(massiv.findIndex(function(item) {
  console.log('findIndex', item);
  return item == "1";
}));

If you really want to use forEach, you can put it in try..catch and throw an error if the element is found.

var massiv = ['2', '1', '3'];
try {
  massiv.forEach(function(item, i) {
    console.log('foreach', i);
    if (item == "1") {
      throw {
        reason: "finded",
        index: i
      }
    }
  });
} catch ({
  reason, index
}) {
  if (reason) {
    console.log(reason, ':', index)
  }
}

Instead of the built-in array functions, you can also use a loop for. In this case, to break the loop, you can use the expression break

 12
Author: Grundy, 2017-01-06 13:02:27

The forEach method does not provide for a stop as in the loop via break.

Use every instead of forEach. When there is false, everything will stop.

This is the most correct way.

massiv.every(function(item, i) {
  if (item == "1") {
    console.log(i);
    return false;
  } else {
    return true;
  }
});
 3
Author: L. Vadim, 2017-01-06 13:04:00

[1, 2, 3].some(function(el) {
  console.log(el);
  return el === 2;
});
 0
Author: Lieutenant Jim Dangle, 2017-01-06 12:48:20

You can stop loop by calling a nonexistent function and catching the error:

var massiv = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

try {
  massiv.forEach(function(item, i, vvv) {
    console.log(item);
    if (item == "5") {
      vvv();
    }
  });
} catch (e) {}
 -1
Author: C.Raf.T, 2017-01-06 12:45:59