How to search for a string in an array in node js script without using a loop?

I want to search for a string in a json array using node js.I want to check for all the occurences of the string in the array and return the array.What all functions are available?

I was thinking of how to do it without using a loop to better the performance?

I tried using includes and matches function but wasn't able to do it.

If anyone has any idea, please reply.

0 2 3,648
2 REPLIES 2

Not applicable

What is wrong with the loop?

For convenience you may use something like the _.each() function from lodash for example, but internally it is still a loop :).

BTW looping through an array has a complexity O(n) which is quite good :).

I think your idea of avoiding a loop for better performance is probably a little premature.

Are you sure the loop is the performance bottleneck in the system?

The array in JavaScript has the filter method or the map method which perform quite well and have been optimized. These have been designed for exactly the use case you describe.

Use THAT, and if it really does not satisfy on performance, you can work on finding some optimizations, like maybe using a Bloom filter , or building a pre-index of the array if it is unchanging. But those are sort of advanced scenarios and only pay off if you are willing to spend one-time compute earlier, and then save the results of that analysis for use at runtime. It doesn't sound like that's what you want.

simpler is better is fastest:

var a = [1, 3, "Buzz", 4, false, 17, "Buzz", "purple", -16, "Buzz", 45, "Buzz", "Apigee"];
var indexes = a
  .map(function(item, ix) { return (item === "Buzz") ? ix : -1; })
  .filter (function(item) { return item > -1; });
console.log('indexes: ' + JSON.stringify(indexes)); // [2,6,9,11]