Doing Hackerrank challenges and looked up a faster solution to a problem than my current one. My understanding of .map and .filter is that they are both O(n) functions. But when executing using filter and map is way faster than two for loops. Why is that?
For reference: My two for loop implementation:
function matchingStrings(strings, queries) {
let countArr = new Array(queries.length).fill(0);
let index = 0;
for(const queryStr of queries){
for(const findStr of strings){
if(queryStr === findStr){
countArr[index] += 1;
}
}
index++;
}
return countArr;
}
Much faster filter and map implementation (from https://gist.github.com/rahul4coding/64023e39017f0a5915a9ff884d18446d)
function matchingStrings(strings, queries) {
return queries.map(x=>strings.filter(y=>y===x).length)
}