为“删除从一个数组项”的基础上完成的状态下的物品的最简单的方法是使用Array.prototype.filter
(具有反转的条件)。
就你而言,由于你如何组织你的数据是很难做到的(把它捆绑在一个字符串中很难处理)。下面是如何我会解决它,但随时组织你的数据从一开始就更好地避免尴尬的转换:通过提取关键字和值
var array1=["4#test#4#T#limited","6#test#6#885#restricted","7#test2#2#2#limited","8#test2#4#3#limited","11#885#1#TT#restricted","15#length#1#taw#restricted","17#885#11#T#limited"];
使数据更容易使用(我也保留一些信息返回到阵列的原始形状):
var saneData = array1.map(function(item, index){
var split = item.split('#');
return {
keyword : split[1],
value: +split[0],
original : item,
originalIndex : index
}
});
排序关键字的数据(所以用相同的关键字的所有项目旁边去对方)和值(因此最大的价值在具有相同关键字的子集中是第一个):
saneData.sort(function(a,b){
if (a.keyword !== b.keyword) {
return a.keyword.localeCompare(b.keyword);
} else {
return b.value - a.value;
}
});
过滤器的阵列,仅保留第一项中的一个子集有相同的关键字:
var filteredData = saneData.filter(function(item, index) {
if (index === 0) return true; // first item is good
return item.keyword !== saneData[index-1].keyword;
});
返回到阵列的原始形式(顺序保存):
var array2 = filteredData.sort(function(a,b){ return a.originalIndex - b.originalIndex; }).map(function(item){ return item.original; });
// Result: ["6#test#6#885#restricted", "8#test2#4#3#limited", "15#length#1#taw#restricted", "17#885#11#T#limited"]
你分裂条件不明确。你可以添加更多的细节。 – Praveen