如何对对象数组按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
相关产品推荐
相关产品推荐

