我的需要是在数组元素与字符串的某些其他元素部分匹配时从数组中删除元素,然后删除该元素。
例如,
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-> Phase-2”恰好在string2“ Proj-> Phase-2-> Tower-1”中,则需要删除string2。即使将string3“ Proj-> Phase-1-> Tower-1”与string1进行比较,也不完全相同。因此,不应将其删除
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句