我有一个字符串数组
我想做的是我想在oneArr和twoArr中找到dataArr的匹配元素,并希望将其删除。
这是我尝试过的代码,但是无法正常工作:
@CustomAnnotation(foo = "${my.value}")
在哪里,请帮忙
答案 0 :(得分:5)
如下使用filter
var dataArr = ["1","3","9"];
var oneArr = ["1","2","5"];
var twoArr = ["4","9"];
oneArr = oneArr.filter( e => dataArr.indexOf(e) == -1);
twoArr = twoArr.filter( e => dataArr.indexOf(e) == -1);
console.log("oneArr = "+oneArr);
console.log("twoArr = "+twoArr);
答案 1 :(得分:1)
splice
方法不会影响当前数组,它会返回一个新数组。
例如(取自MDN):
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myFish.splice(3, 1);
// removed is ["mandarin"]
// myFish is ["angel", "clown", "drum", "sturgeon"]
您将需要执行以下操作:
updateData(dataArr){
const newArrOne = [];
const newArrTwo = []
for (let index = 0; index < dataArr.length; index++) {
let orgIndx = oneArr.findIndex(dataArr[index]);
newArray = oneArr.splice(orgIndx,1);
let orgIndx1 = twoArr.findIndex(dataArr[index]);
newArrTwo = twoArr.splice(orgIndx1,1);
}
console.log(newArrOne);
console.log(newArrTwo);
}
请注意,以上代码与生产代码完全不同,仅基于您提供的代码。
您还可以使用Harunur Rashid解释的过滤方法
答案 2 :(得分:1)
for (var index = 0; index < dataArr.length; index++) {
let orgIndx = oneArr.indexOf(dataArr[index]);
if (orgIndx >= 0) oneArr.splice(orgIndx, 1);
let orgIndx1 = twoArr.indexOf(dataArr[index]);
if (orgIndx1 >= 0) twoArr.splice(orgIndx1, 1);
}
答案 3 :(得分:0)
您所犯的错误是,您正在将字符串作为参数传递给findIndex函数,但它希望将函数作为参数。参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
如果您想通过使用查找索引来修复当前代码,则可以按照以下步骤进行操作:
updateData(dataArr){
for (let index = 0; index < dataArr.length; index++) {
let orgIndx = oneArr.findIndex((element)=>{
return element==dataArr[index]
});
if(orgIndx!=-1)
oneArr.splice(orgIndx,1);
let orgIndx1 = twoArr.findIndex((element)=>{
return element==dataArr[index]
});
if(orgIndx1!=-1)
twoArr.splice(orgIndx1,1);
}
}
在上面的示例中,我通过提供函数作为findIndex函数的参数来修改您的逻辑,并且还在拼接之前检查index = -1,因为如果在数组中没有找到满足条件的元素,则findIndex返回-1函数已通过。