Reputation: 139
here I want to clear those rows by pressing and selecting the DeleteRow button, the problem is that if I select rows from the top of the list, they will be removed without problems, but if the rows are from Selection down to top, selected rows cannot be deleted.
handleMultipleDelete = () =>{
const arr=this.state.selectRowList;
const product = this.state.productList;
for (let i=arr.length-1; i>=0; i-- ){
product.splice(arr[i], 1);
}
this.setState({
productList: product,
selectRowList: [],
});
}
My code is here
Upvotes: 0
Views: 495
Reputation: 361
As shown in your code, you've used the splice method. The splice method in fact affects the original array you are dealing with. So I would not recommend that.
Instead what you can do is, use the filter method of Array.
Something like this:
handleMultipleDelete = () => {
const arr = this.state.selectRowList;
const product = this.state.productList;
const newProductArr = product.filter((product, index) => {
return !arr.includes(index);
});
this.setState({
productList: newProductArr,
selectRowList: []
});
};
Hope it helps :)
Upvotes: 0
Reputation: 468
You just need to sort the arr before deleting as they are the indexes of an array.
Here is the updated function
handleMultipleDelete = () => {
const arr = this.state.selectRowList;
const product = this.state.productList;
arr.sort(function(a, b) {
return a - b;
});
for (let i = arr.length - 1; i >= 0; i--) {
product.splice(arr[i], 1);
}
this.setState({
productList: product,
selectRowList: []
});
};
Here is the updated fork.
Upvotes: 1
Reputation: 30360
You could achieve this via Array#filter()
as shown by the following:
handleMultipleDelete = () => {
const { selectRowList, productList } = this.state;
// Filter product array ..
const newProduct = productList.filter((product, index) => {
// ..where product's index does not exist in selectRowList
return selectRowList.some(select => index === select) === false
});
this.setState({
productList: newProduct,
selectRowList: [],
});
}
By filtering the product
array (rather than removing items per iteration of arr
via Array#splice
), this ensures that the original product indicies remain intact and consistent with the indicies in the selectRowList
array during the filtering (ie removing unwanted items) stage.
Hope that helps!
Upvotes: 0