0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.