What is the highest performance way to filter a list of JSON objects in JavaScript?

后端 未结 4 1427
感动是毒
感动是毒 2020-12-25 13:45

Let\'s assume I have a huge (1000+) list of objects like this:

[{name: \'john dow\', age: 38, gender:\'m\'}, {name: \'jane dow\', age: 18, gender:\'f\'}, ..]         


        
4条回答
  •  甜味超标
    2020-12-25 14:18

    From simple to more complex (no additional libs):

    1. Limit search for minimum x chars (usually 3 is acceptable)
    2. Delay the filtering while the user is typing using timeout:
    //clear previous timed filtering
    if (typingTimeout) {
          clearTimeout(typingTimeout);
          typingTimeout = null;
        }
    //schedule new filtering
    typingTimeout = setTimeout(() => {
       // do some filtering
    }, 2000); //acceptable 1-2s
    
    1. If you still wish for faster filtering, You can group your list alphabetically in an object:
    {
       A: ['Aron', 'Arnold', ...],
       B: ['Baby'],
       ....
    }
    

    Then filter them using the prefixed lists with the first char entered. It is just an example, you should group your data as you see fit (maybe first 2 letters...).

    Here is a function that I implemented to help prefix my array:

    export function prefixStringsArray(arr, prefixLength) {
      const prefixArr = arr.map((s) => s.substr(0, prefixLength));
      const filter = (item, query) =>
        item.toLowerCase().startsWith(query.toLowerCase());
    
      const prefixObj = {};
      for (const pre of prefixArr) {
        prefixObj[pre] = arr.filter((item) => filter(item, pre));
      }
    
      return prefixObj;
    }
    

    You should know that using JS object is a very good bet because they are accessed in O(1) (it is sort of a hash map) and if you group your data optimally you'll get small arrays to filter.

    Notes:

    1. If you choose to prefix your array you should watch out for the user searching query.length < prefixLength
    2. This gave me great results in mobile development (React native)
    3. The code is only a draft - manually tested

提交回复
热议问题