Home > Mobile >  Efficient way to retrieve the array items those begin with a string
Efficient way to retrieve the array items those begin with a string

Time:09-16

I have a js array where I need to get the sub array that has only those items starting with the string "outh2."

This solution gives the result but I am looking for a efficient or built-in function if any?

const result = ["oauth2.Hubspot1", "oauth1.Hubspot", "oauth2.Hubspot", "oauth2.HubSpot", "something else"].filter(function(key) {
  if (key.indexOf("oauth2.") == 0) return true;
});

console.log(result);

The expected value is

["oauth2.Hubspot1","oauth2.Hubspot","oauth2.HubSpot"]

CodePudding user response:

You can use startsWith function:

[
  "oauth2.Hubspot1",
  "oauth1.Hubspot",
  "oauth2.Hubspot",
  "oauth2.HubSpot",
  "something else"
].filter(key => key.startsWith("oauth2."));

CodePudding user response:

Your solution should be "good enough" for arrays with fewer than 100,000 items. You should test your code's performance first to avoid micro-optimization.

const arr = Array.from({length: 100000}, (_, i) => `oauth2.Hubspot${i}`);

const t0 = performance.now()
const res0 = arr.filter(function(key) {
    if (key.indexOf("oauth2.") == 0) return true;
});
const t1 = performance.now()
const res1 = arr.filter(key => key.startsWith("oauth2."));
const t2 = performance.now()

console.log(`Original: ${t1-t0}ms`);
console.log(`startsWith: ${t2-t1}ms`);

  • Related