【问题标题】:Sort a json data with respect to user input根据用户输入对 json 数据进行排序
【发布时间】:2021-08-09 23:35:27
【问题描述】:

我想使用 javascript 对 json 数据进行排序,条件是用户将输入一个输入值,并根据 json 数组中出现的输入值显示一个输出。 例如:如果用户输入是 userInput ="Man" 并且 json 数据是

var objs = [ 
{ first_nm: 'Mango raw'},
{ first_nm: 'Devgad Mango'},
{ first_nm: 'Mantra santra'},
{ first_nm: 'Prag Mango'},
{ first_nm: 'Pirate aam Mango'}];

输出列表应显示为

  1. first_nm: '芒果原料'
  2. first_nm: 'Mantra santra'
  3. first_nm: 'Devgad 芒果'
  4. first_nm: 'Prag Mango'
  5. first_nm: '海盗 aam 芒果'

我尝试使用比较功能,但它以升序对记录进行排序,而不是相对于用户输入。

【问题讨论】:

    标签: javascript arrays json sorting


    【解决方案1】:

    最简单的方法是遍历字符串列表并创建一个新数组,其中包含以用户输入开头的字符串。然后我们可以对匹配项进行排序并将不匹配的字符串数组附加到这个列表中。

    var users = [{
        name: 'Devgad Mango'
      },
      {
        name: 'Mantra santra'
      },
      {
        name: 'Prag Mango'
      },
      {
        name: 'Pirate aam Mango'
      }, {
        name: 'Mango raw'
      },
    ];
    
    function search(input) {
      const matches = [];
      const remeinder = [];
      users.forEach(user => {
        user.name.startsWith(input) ?
          matches.push(user) :
          remeinder.push(user);
      });
      console.log(matches, remeinder)
    
      // now we sort the matches
    
      matches.sort((a, b) => {
        const aa = a.name.toLowerCase();
        const bb = b.name.toLowerCase();
        if (aa < bb) {
          return -1;
        }
        if (aa > bb) {
          return 1;
        }
        return 0;
      });
    
      console.log(matches);
    
      // now we want to push the remeinders to the end of the sorted array.
    
      matches.push(...remeinder);
    
      console.log(matches);
    }
    
    search('Man')

    【讨论】:

    • 但是如果用户输入小写,上述解决方案在这种情况下不起作用
    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多