Mdd Mdd - 29 days ago 10
Javascript Question

Fastest method to filter an array for typeahead

I am wondering what the fastest way to filter an array of objects for a typeahead is?

Given a list of 10000 or more items similiar to this:

[{name: "ben"}, {name: "Alex"}, {name: "mary"}]


I can filter them for a typeahead using the
Array.prototype.filter
method, but I'm seeing quite a bit of lag time before getting results back. Is there a better way to filter large lists based on keyboard input?

Here is my current implemenation:

const list = [{...}] //list of 10000 or more objects with a name property

function getFilteredList(input) {
const reg = new RegExp(input.toLowerCase(), 'i');
return list.filter(i => reg.test(i.name));
}


Is there a way to filter a list that is faster or has better performance than using the
Array.prototype.filter
method?

Answer

Doing a couple of tests, seems like all traditional loop is three times (more or less) faster for big arrays than filter though much more verbose. I think I'd stick to filter just for clarity's sake.

const list = []; //list of 10000 or more objects with a name property
var res;

for (var i = 0; i < 1000000; i++) {
  list.push({
    name: "a" + i
  });
}

function getFilteredList(input) {
  const reg = new RegExp(input.toLowerCase(), 'i');
  return list.filter(i => reg.test(i.name));
}

function getFilteredList2(input) {
  const reg = new RegExp(input.toLowerCase(), 'i');
  let len = list.length;
  let i = 0;
  let res = [];
  let el;
  
  while (i !== len) {
    el = list[i++]; 
    if (reg.test(el.name)) {
      res.push(el);
    }
  }
  return res;
}

console.time("Filter test");
res = getFilteredList('a999999');
console.timeEnd("Filter test");
console.log(res[0]);

console.time("Filter test2");
res = getFilteredList2('a999999');
console.timeEnd("Filter test2");
console.log(res[0]);

Comments