Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of javascript Array.prototype.filter()?

Tags:

javascript

What is the big O of Array.protoype.filter?

I have looked at the documentation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) but haven't been able to work it out.

like image 566
timothyylim Avatar asked Nov 06 '16 07:11

timothyylim


People also ask

What is the time complexity of array filter?

At this moment, the time complexity is O(n), linear time, where n is the size of fahrenheit array. Then we apply the result of map function to filter function. The time complexity of the filter function is O(n) as well.

What is time complexity of JavaScript array find?

The time complexity of Array. prototype. find is O(n) (with n being the array's length), and it's fair to assume that it will remain that way. Generally speaking, it's often impossible for engines to improve the complexity class of an operation.

Is JavaScript filter slow?

To our surprise, for-loops are much faster than the Array. filter method. To be precise, the Filter method is 77% slower than for loop.


1 Answers

O(N)

Example:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => isBig(word));

function isBig(word){
  	console.log("called");
	return word.length > 6;
}

Output:

"called" "called" "called" "called" "called" "called" Array ["exuberant", "destruction", "present"]

like image 126
Saurabh Vaidya Avatar answered Oct 06 '22 13:10

Saurabh Vaidya