Thursday, 9 April 2020

javascript filter vs every vs foreach

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
Array.prototype.every will return true if every element in the array matches your condition in the callback
function isBigEnough(element, index, array) {
  return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);

The forEach() method calls a function once for each element in an array, in order.

https://www.w3schools.com/jsref/jsref_foreach.asp
https://stackoverflow.com/questions/21472220/difference-between-every-and-filter-in-javascript

No comments:

Post a comment