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"]

Answer from Saurabh Vaidya on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 66980888 › does-javascript-have-a-filter-function-with-a-time-complexity-of-olog-n
performance - Does Javascript have a filter function with a time complexity of O(log n)? - Stack Overflow
However, since my array of strings is already sorted in alphabetical ordered, this task could theoretically be accomplished in O(log n) time. Is there any alternative Javascript ...
Discussions

javascript - Time complexity of filter with a nested loop - Stack Overflow
It should be O(m ^ 2 * n) where m is the number of keys. 2021-12-30T12:14:25.457Z+00:00 ... The lambda is executed for every item in items. The lambda iterates over every key in an item and prints it. The time complexity is therefore O(n*m) for n = number of items and m = number of keys per item. More on stackoverflow.com
🌐 stackoverflow.com
December 30, 2021
How do you find time complexity when using Javascript array methods
I believe this one is effectively quadratic. Or to be specific, O(mn), where m = arr.length and n = arr2.length. Filter is linear if its callback is constant. But in this case the callback is also linear. if the arrays increase in length the time would also increase. You can only deduce that it's not constant from this. It doesn't tell you whether it's linear, logarithmic, exponential, quadratic, etc. If arr2 is sorted, you could improve the runtime by using a binary search on it. If both arrays are sorted, I'm pretty sure you could make this effectively linear, though I'm not sure how you'd write that functionally. More on reddit.com
🌐 r/webdev
8
1
July 22, 2023
JavaScript runtime complexity of Array functions - Stack Overflow
Is the runtime complexity defined by the JS standard on common Array functions like push, pop, shift, slice or splice? Esp. I'm interested in removing and inserting entries at random positions. If ... More on stackoverflow.com
🌐 stackoverflow.com
March 4, 2021
How to improve the performance of filtering an array that has 30k element?
I doubt it is the filtering itself that is particularly slow. About the only thing to optimize in your filter is to not call to Lower multiple times per item. Rather, what I think is likely the issue is that your ui doesn't handle the data well once you hit a certain number of items it tries to display. You should confirm this by testing the filtering of the items independently of the ui rendering those results. More on reddit.com
🌐 r/learnjavascript
33
11
June 15, 2023
🌐
Quora
quora.com › How-would-you-measure-time-complexity-for-in-built-functions-For-eg-filter-method-in-JavaScript-would-be-O-1-or-O-n
How would you measure time complexity for in-built functions? For eg. filter() method in JavaScript would be O(1) or O(n)? - Quora
Answer (1 of 3): Well, ideally the time complexity would be documented. This is the case for the C++ standard library. In the case of [code ]filter()[/code] we can reason that it must take at least N calls to the function you passed in, but the cost of that function is not under [code ]filter[/c...
🌐
JavaScript in Plain English
javascript.plainenglish.io › under-the-hood-worst-case-complexities-workings-of-popular-js-array-methods-739d5fef314a
Worst Case Complexities & Workings of Popular JS Array Methods | JavaScript in Plain English
August 9, 2022 - All elements of the array maybe changed in linear time. ... The method returns the modified array. The filter()method creates a shallow copy that includes all the elements which pass the filter function.[22]
🌐
Medium
randyperkins2k.medium.com › evaluating-time-complexity-of-native-javascript-methods-3f57f4d922f0
Evaluating Time Complexity of Native JavaScript Methods | by Randolph Perkins | Medium
December 14, 2020 - Therefore I have found it instructive to research a few commonly used methods and compile the results in one place. Hence the writing of this post! What follows are a few such methods in JavaScript, and a brief description of their characteristics as relating to their time and space complexity.
🌐
Swift by Sundell
swiftbysundell.com › basics › time-complexity
Time Complexity | Swift by Sundell
August 9, 2019 - Since the above filter operation requires us to iterate through each element within the events array, it has a time complexity of O(n) — where n refers to the number of events that our function will be operating on.
Find elsewhere
Top answer
1 of 3
186

The ECMA specification does not specify a bounding complexity, however, you can derive one from the specification's algorithms.

push is O(1), however, in practice it will encounter an O(N) copy costs at engine defined boundaries as the slot array needs to be reallocated. These boundaries are typically logarithmic.

pop is O(1) with a similar caveat to push but the O(N) copy is rarely encountered as it is often folded into garbage collection (e.g. a copying collector could only copy the used part of an array).

shift is at worst O(N) however it can, in specially cases, be implemented as O(1) at the cost of slowing down indexing so your mileage may vary.

slice is O(N) where N is end - start. Not a tremendous amount of optimization opportunity here without significantly slowing down writes to both arrays.

splice is, worst case, O(N). There are array storage techniques that divide N by a constant but they significantly slow down indexing. If an engine uses such techniques you might notice unusually slow operations as it switches between storage techniques triggered by access pattern changes.

One you didn't mention, is sort. It is, in the average case, O(N log N). However, depending on the algorithm chosen by the engine, you could get O(N^2) in some cases. For example, if the engine uses QuickSort (even with an late out to InsertionSort), it has well-known N^2 cases. This could be a source of DoS for your application. If this is a concern either limit the size of the arrays you sort (maybe merging the sub-arrays) or bail-out to HeapSort.

2 of 3
18

in very simple words

push -> O(1)

pop -> O(1)

shift -> O(N)

slice -> O(N)

splice -> O(N)

Here is a complete explanation about time complexity of Arrays in JavaScript.

🌐
GeeksforGeeks
geeksforgeeks.org › es6-array-filter-method
ES6 | Array filter() Method | GeeksforGeeks
May 28, 2022 - index(Optional): The index of the current element being processed in the array. array(Optional): The array filter was called upon. thisArg(Optional): Value to use as this when executing the callback. Example 1: The filter function filters all the numeric values in the array greater than 5 · javascript · var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var result = numbers.filter(number => number > 5); console.log(result); Output : [ 6, 7, 8, 9, 10 ] Time complexity: O(n) Auxiliary Space: O(1) Example 2: The filter function filters all the words in the array which have length greater than 5 ·
🌐
Plain English
plainenglish.io › blog › are-for-loops-better-than-arrays-filter-or-foreach-methods
Are JavaScript for loops better than filter() and forEach?()
November 15, 2020 - One reason could be that for-loops run synchronously, and the filter method is creating 1 new function for each element in the array. This new function is then put on the call stack, and run one by one by the event loop. This overhead takes time, which the for-loop completely omits, and runs your operations right there in the same function. It is clear that the for-loop is the clear winner for pure performance if we look at the metric of operations per second, or time.
🌐
SKOUMAL
skoumal.com › blog › performance of built-in higher-order functions map, filter, reduce, and flatmap vs. for-in loop in swift
Performance of Map, Filter, Reduce, and flatMap vs. for-in loop in Swift
December 22, 2023 - In other words, in the worst case, the result of filter function can be O(n), which means nothing was filtered out and this result is used as input of reduce function. In the end, the time complexity is O(3n).
🌐
JavaScript in Plain English
javascript.plainenglish.io › understanding-time-and-space-complexity-of-common-javascript-built-in-methods-39a3285a6409
Understanding Time and Space Complexity of Common JavaScript Built-in Methods | by Kyle Le | JavaScript in Plain English
April 14, 2023 - When writing JavaScript code, it’s important to consider the performance of the code you’re writing. One way to do this is to understand the time and space complexity of the built-in methods you’re using.
🌐
Reddit
reddit.com › r/learnjavascript › how to improve the performance of filtering an array that has 30k element?
r/learnjavascript on Reddit: How to improve the performance of filtering an array that has 30k element?
June 15, 2023 -

I'm using vuejs 2. I basically have an input box of which when I type in it, it gives me a drop down of the list of element I searched for, so say I searched for "foo" it will filter through the array of all items that has the name foo in them but if I search for "foo bar" it should give me the list of items that have the name "foo" or "bar" or "foo bar". This is business reasons.

The array of items has 30k records, this is the code I am using to do the filtering:

let keyWordsTyped = ["foo", "bar"]; // the searched keywords are placed in an array
items = items.filter((item) => { keyWordsTyped.some((keyword) => { 
            item.name.toLowerCase().includes(keyword)})})
        .map(item => {highlightItem(item)});

The thing is if I search for a single term like "foo" it works fine, the speed is fine. HOWEVER, if I search for "foo bar" it get way too slow and laggy, I guess this is because when I search for a single word the returned array is small, but if I search for two words it gets much bigger.

Is there any way to make this faster??

🌐
DEV Community
dev.to › lukocastillo › time-complexity-big-0-for-javascript-array-methods-and-examples-mlg
Time complexity Big 0 for Javascript Array methods and examples. - DEV Community
June 3, 2020 - For best-case big-omega is used (e.g., Ω(n)) and for average-case big-theta is used (e.g., Θ(n)). Notice the internal ligature of the big-theta vs that of a big O as it may be easy to mistake one for the other. ... What reference did you lean on to find their time complexity?
🌐
Medium
tharinducs.medium.com › time-complexity-of-objects-and-arrays-js-algo-02-5cd8ead23b91
Time Complexity of Objects and Arrays — JS Algo 02 | by Tharindu Senadheera | Medium
February 18, 2023 - forEach / map/filter / reduce — O(n) That’s an overview of time complexity in Arrays and Objects. See you in the next article. JavaScript · Algorithms · Arrays · Objects · Time Complexity · 33 followers · ·59 following · Senior Software Engineer @Euka Future Learning ·
🌐
DEV Community
dev.to › twinfred › completing-4-javascript-filter-method-challenges-16df
Completing 4 JavaScript .filter() Method Challenges - DEV Community
June 7, 2021 - The Javascript array filter() creates a new array of elements from an existing array that meets a specified condition. Time Complexity: O(n) I decided to challenge myself with the .filter() method first because it's super useful when it comes to dealing with data.