'Does the .includes method in JavaScript loop through the array and case O(n)?
Does the .includes method cause O(n^2) when run with another loop such as in this simple example?
function myFn(){
let age = people.map(person => {
if(person > 21){
return "YES";
} else {
return "NO";
}
return age.includes('NO') ? 'NO' : 'YES';
}
Solution 1:[1]
The method is specified such that it does indeed go through the array element by element. So that's O(n) (linear). But that's after your map
, which has already gone all the way through the array.
JavaScript engine implementations are free (as always) to optimize provided optimizing doesn't change the semantics of the method.
As a side note, though, if you want to look through an array for an element matching an arbitrary condition, map
+includes
isn't your best choice; some
and every
are better, because they short-circuit (stop looping) when they find an element that passes (some
) or fails (every
) the test. Your code looks to see if every element in people
is > 21
, so that would be:
function myFn() {
return people.every(person => person > 21) ? "YES" : "NO";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |