skip to Main Content

This is my array

0:0 {value: 123}
0:1 {value: 124}
0:2 {value: 124}

1:0 {value: 120}
1:1 {value: 121}
1:2 {value: 124}

2:0 {value: 123}
2:1 {value: 121}
2:2 {value: 124}

<div onClick={()=>onRemoveVariation(0, 2)}Remove</div>

And this is my code

const onRemoveVariation = (index1, index2) => {
    setVariants(
      variants.map((data, i) => {
        data.map((d, ix) => {
          if (i === index1 && ix === index2) {
            //Delete the entire row
          }
          return d;
        })
        return data;
      })
    );
  }

I used filter function for single array, but don’t know how to use 2d array.

If want to delete entire row if index 1 and index 2 match. How to solve this?
Thanks

2

Answers


  1. The splice method would fit your situation if you just only manage the row of your array

    quantityElements for how many rows, you want to delete and the index arg where you want to start your row in the array

    Should you try this code block;

    const onRemoveVariation = (index, quantityElements ) => {
        setVariants(prev => 
          prev.splice(index, quantityElements)
        );
      }
    
    Login or Signup to reply.
  2. You can remove a row, for instance by using the filter function.

    const onRemoveVariation = (index1, index2) => {
      setVariants(variants.map((data, i) => {
        if (i === index1) {
          return data.filter((d, ix) => ix !== index2);
        }
        return data;
      }));
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search