如何获取数组中'importo'的所有索引并仅保留首个实例?
问题:查找数组中特定值的所有索引并仅保留第一个匹配项
我通过以下代码构建了一个数组:
var intestColonne = []; $('.tbi').find('tr:first th').each(function(){ intestColonne.push(($(this).children('select').val())); }); //intestColonne=intestColonne.pop(); //if this row is parsed the array becomes undefined
现在我想要检查数组中是否存在特定值的多个条目:
if(intestColonne.filter(x => x === "importo").length>1){ //check the index of each "importo" element //store it into variables //remove all the other "importo" leaving only the first (lowest index) }
我卡在了第一步,因为找不到能返回所有'importo'值索引的特定函数。indexOf会返回第一个索引,lastIndexOf会返回最后一个索引。使用indexOf可以指定起始查找位置,但这很难满足我的需求。有没有其他可用的搜索方式?
解决方案
1. 获取所有匹配值的索引
你可以用Array.prototype.forEach()遍历数组,把符合条件的索引收集起来:
const targetValue = "importo"; const indices = []; intestColonne.forEach((value, index) => { if (value === targetValue) { indices.push(index); } });
这样indices数组里就会存所有值为importo的元素的索引,比如[2,5,7]这类格式。
2. 保留第一个匹配项,删除其余的
拿到索引数组后,要从后往前删除元素——如果从前往后删,前面元素被移除后,后续元素的索引会偏移,导致删除操作出错。
if (indices.length > 1) { // 跳过第一个索引,从最后一个匹配索引开始倒序删除 for (let i = indices.length - 1; i >= 1; i--) { intestColonne.splice(indices[i], 1); } }
这样就能确保只保留索引最小的那个importo元素,其余匹配项都会被移除。
整合后的完整代码
var intestColonne = []; $('.tbi').find('tr:first th').each(function(){ intestColonne.push(($(this).children('select').val())); }); const targetValue = "importo"; const indices = []; intestColonne.forEach((value, index) => { if (value === targetValue) { indices.push(index); } }); if (indices.length > 1) { for (let i = indices.length - 1; i >= 1; i--) { intestColonne.splice(indices[i], 1); } }
内容的提问来源于stack exchange,提问作者user2399035
相关产品推荐
相关产品推荐

