Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between every and filter in javascript?

I was wondering which of the functions among Array.prototype.every and Array.prototype.filter are fast in javascript? The difference that I know is that every can be stopped by returning false and filter cannot stop by returning false. Apart from this difference is there any other? And if which one among this has indexing?

like image 808
Uday Reddy Avatar asked Jan 31 '14 04:01

Uday Reddy


People also ask

What is the difference between every and filter in JavaScript?

The difference that I know is that every can be stopped by returning false and filter cannot stop by returning false.

What is the difference between every and some in JavaScript?

every() method in JavaScript is used to check whether all the elements of the array satisfy the given condition or not. The Array. some() method in JavaScript is used to check whether at least one of the elements of the array satisfies the given condition or not.

What is the difference between filter and map in JavaScript?

map creates a new array by transforming every element in an array individually. filter creates a new array by removing elements that don't belong.

What is every in JavaScript?

Definition and Usage. The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.


1 Answers

The functions do completely different things.

Array.prototype.filter will create an array of all the elements matching your condition in the callback

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);
// passed is true
like image 107
migvill Avatar answered Oct 02 '22 19:10

migvill