[英]JS double array remove element
I want to remove an element (an array) from an array (an array of arrays). 我想从一个数组(一个数组的数组)中删除一个元素(一个数组)。
car = [carId, brand, year]; //array
selectedCars = []; //array of arrays
This is what i have tried, but the comparison never gets true, although it should. 这是我尝试过的方法,但是尽管如此,但比较从未实现。
function removeElementFromArray(carsArray, car){
var i;
for(var k = 0; k < carsArray.length; k++){
if(carsArray[k][0] == car[0]){
i=k;
}
}
var index = carsArray.indexOf(i);
if(index != -1) {
carsArray.splice(index, 1);
}
}
carsArray.indexOf(i)
will never find anything. carsArray.indexOf(i)
永远找不到任何东西。 carsArray
is an array of arrays, i
is the index where a match was found, not an array. carsArray
是数组的数组, i
是找到匹配项的索引,而不是数组。
You don't need to call indexOf()
, the for
loop already found the index you want. 您无需调用
indexOf()
, for
循环已找到所需的索引。 You just need to test whether it found anything. 您只需要测试它是否发现了任何东西。
if (index !== undefined) {
carsArray.splice(index, 1));
}
You also should put break;
您还应该
break;
in your loop, so you stop searching once you find a match. 在循环中,因此一旦找到匹配项,您就停止搜索。
In fact, you could just do the splice in the loop. 实际上,您可以在循环中进行拼接。
for (var i = 0; i < carsArray.length; k++) {
if (carsArray[k][0] == car[0]) {
carsArray.splice(k, 1);
break;
}
}
You can try using the array .every
method for your comparison, along with .findIndex
if you can use es6: 您可以尝试使用数组
.every
方法进行比较,如果可以使用es6,则可以与.findIndex
一起使用:
car = ["carId", "brand", "year"]; //array selectedCars = [["carId", "brand", "year"], ["otherCarId", "brand", "year"]]; //array of arrays function removeCar(selected, car) { const index = selected.findIndex(selectedCar => selectedCar.every((val, i) => val === car[i])); if (index !== undefined) selected.splice(index, 1); return selected; } console.log(selectedCars); removeCar(selectedCars, car); console.log(selectedCars);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.