You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组排序:如何让搜索结果的精确匹配项置顶?

问题描述

我的数据库中有用于搜索栏的数据,表中字段为searchPeople(全小写),数据格式为Name##CityName,示例数据如john##rome、romeu##napoli等。当用户在搜索栏输入Rome时,会匹配姓名或城市包含Rome的条目,但目前结果按数据库随机顺序返回,希望将姓名或城市与搜索词**精确匹配(===)**的条目排在数组最前面,例如{name: 'John', city: 'Rome'}应排在首位。现有如下示例数组,如何排序该数组以实现相关度高的结果置顶?

const people = [{
    name: 'Romeu',
    city: 'Napoli'
  },
   {
    name: 'John',
    city: 'Rome' // 此对象应排在首位,因为存在精确匹配
  },
  {
    name: 'Romeu2',
    city: 'Milan'
  }
];

console.log(people);

// 如何排序people数组让相关度最高的结果在顶部?

解决方案

可以利用数组的sort()方法,通过自定义排序规则实现优先级排序,核心思路是给不同匹配程度的条目分配不同优先级,再按优先级降序排列:

完整代码示例

const searchTerm = 'Rome'.toLowerCase(); // 统一转为小写,和数据库字段格式对齐
const people = [{
    name: 'Romeu',
    city: 'Napoli'
  },
   {
    name: 'John',
    city: 'Rome'
  },
  {
    name: 'Romeu2',
    city: 'Milan'
  }
];

const sortedPeople = people.sort((a, b) => {
  // 计算单个条目的优先级
  const getPriority = (item) => {
    const nameLower = item.name.toLowerCase();
    const cityLower = item.city.toLowerCase();
    // 精确匹配优先级最高
    if (nameLower === searchTerm || cityLower === searchTerm) {
      return 3;
    }
    // 包含匹配优先级次之
    else if (nameLower.includes(searchTerm) || cityLower.includes(searchTerm)) {
      return 2;
    }
    // 其他情况(当前场景已过滤出匹配结果,此分支可忽略)
    return 1;
  };

  const priorityA = getPriority(a);
  const priorityB = getPriority(b);

  // 降序排列,优先级高的条目排在前面
  return priorityB - priorityA;
});

console.log(sortedPeople);

代码说明

  1. 大小写统一:将搜索词和条目的姓名、城市都转为小写,避免数据库全小写字段与用户输入的大小写差异影响匹配;
  2. 优先级分配:给精确匹配的条目分配最高优先级(3),包含匹配的条目分配次优先级(2);
  3. 排序逻辑:通过sort()方法比较两个条目的优先级数值,让数值高的条目排在数组前面,实现相关度高的结果置顶。

内容的提问来源于stack exchange,提问作者asfafafags

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:40:33