我需要从数组中删除元素,当数组元素与字符串的其他元素部分匹配时,删除该元素。
例如,
var res1 = [
" Proj -> Phase-1 -> Tower-1 -> Floor-2 ",
" Proj -> Phase-2 ",
" Proj -> Phase-2 -> Tower-1 " ];也就是说如果我的
res1[2]="Proj->Phase-2->Tower-1" 和
res1[1]="Proj->Phase-2"res1[1]与res1[2]部分匹配。所以我需要删除res1[2]。之后,我想要剩余的数组值。但它不能正常工作。
以下是我尝试过的,但我并没有得到预期的结果:
for (i = 0; i < res1.length; i++) {
for (j = 0; j < res1.length; j++) {
if (res1[i] != res1[j]) {
if (res1.indexOf(res1[j]) === 0) {
console.log(res1);
console.log(res1[j]);
delete res1[i];
}
}
}
}也就是说,如果string1“Proj->相位-2”恰好在string2“Proj->相位-2->Tower-1”中,那么string2就需要删除。即使string3的“Proj->相位-1->塔-1”与string1相比,也不是完全相同的。所以不应该移除
发布于 2016-07-09 14:56:36
var res1 = [
" Proj -> Phase-1 -> Tower-1 -> Floor-2 ",
" Proj -> Phase-2 ",
" Proj -> Phase-2 -> Tower-1 " ];
for (var i = 0; i < res1.length; i++) {
for (var j = i + 1; j < res1.length; j++) {
if (res1[j].includes(res1[i])) {
res1.splice(j, 1);
j--; // Splice deletes the element so all index shifts, need to recheck the same element
}
}
}
console.log(res1)
发布于 2016-07-09 15:21:17
你差点就到了。只要检查一下索引是否是相同的
i !== j如果一个字符串在另一个字符串中
res1[i].indexOf(res1[j]) === 0
// ^^^然后使用Array#splice删除元素。
当foor循环增量为1,而外部循环的实际元素被删除时,您需要对索引i进行更正。然后需要一个break,因为结构发生了变化,需要用j初始化一个新的循环。
var res1 = [" Proj -> Phase-1 -> Tower-1 -> Floor-2 ", " Proj -> Phase-2 ", " Proj -> Phase-2 -> Tower-1 "],
i, j;
for (i = 0; i < res1.length; i++) {
for (j = 0; j < res1.length; j++) {
if (i !== j && res1[i].indexOf(res1[j]) === 0) {
res1.splice(i, 1);
i--;
break;
}
}
}
console.log(res1);
发布于 2016-07-09 16:38:46
使用EcmaScript2015的解决方案:
var res1 = [
" Proj -> Phase-1 -> Tower-1 -> Floor-2 ",
" Proj -> Phase-2 ",
" Proj -> Phase-2 -> Tower-1 " ];
res1 = res1.filter((x, i) => res1.every((y, j) => i==j || x.indexOf(y)));
console.log(res1);
或者在没有箭头函数的情况下也是这样:
var res1 = [
" Proj -> Phase-1 -> Tower-1 -> Floor-2 ",
" Proj -> Phase-2 ",
" Proj -> Phase-2 -> Tower-1 " ];
res1 = res1.filter(function(x, i) {
return res1.every(function(y, j) {
return i==j || x.indexOf(y);
})
});
console.log(res1);
https://stackoverflow.com/questions/38281467
复制相似问题