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

如何对对象数组按name字段实现前缀匹配与包含匹配过滤?

按名称字段实现数组过滤的方案

给定如下对象数组:

const test = [
  { id: 1, name: 'Taliparamba Co Op Hospital' },
  { id: 2, name: 'Athikkal Saw Mill,Kallai' },
  { id: 3, name: 'Marhaba Ice Plant Atholi' }
];

1. 前缀匹配实现

前缀匹配要求搜索字符串与名称开头部分匹配,忽略大小写差异。可以通过统一转小写后使用startsWith方法实现:

function prefixFilter(arr, keyword) {
  const lowerKeyword = keyword.toLowerCase();
  return arr.filter(item => item.name.toLowerCase().startsWith(lowerKeyword));
}

// 示例调用
console.log(prefixFilter(test, 'tali'));
// 输出:[{ id: 1, name: 'Taliparamba Co Op Hospital' }]

console.log(prefixFilter(test, 'tali Co OP'));
// 输出:[{ id: 1, name: 'Taliparamba Co Op Hospital' }]

2. 包含匹配实现

包含匹配要求搜索字符串出现在名称任意位置,同样忽略大小写,使用includes方法即可:

function includeFilter(arr, keyword) {
  const lowerKeyword = keyword.toLowerCase();
  return arr.filter(item => item.name.toLowerCase().includes(lowerKeyword));
}

// 示例调用
console.log(includeFilter(test, 'ath'));
// 输出:
// [
//   { id: 2, name: 'Athikkal Saw Mill,Kallai' },
//   { id: 3, name: 'Marhaba Ice Plant Atholi' }
// ]

如果需要一个函数同时支持两种模式,可以增加参数区分:

function filterByName(arr, keyword, mode = 'include') {
  const lowerKeyword = keyword.toLowerCase();
  if (mode === 'prefix') {
    return arr.filter(item => item.name.toLowerCase().startsWith(lowerKeyword));
  }
  return arr.filter(item => item.name.toLowerCase().includes(lowerKeyword));
}

// 前缀匹配调用
filterByName(test, 'tali', 'prefix');
// 包含匹配调用
filterByName(test, 'ath');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:29:59