1

I am trying to remove a value by Index of the props array passed from another component.

[...this.props.data].splice([...this.props.data].indexOf(oldData), 1)
const {tableData, ...application} = oldData;
this.props.deleteData(application);

It deletes the data, but not just the selected value, but both values at the same time. I guess the problem is in the splice..indexOf

oldData :is the selected row that needs to be deleted.
2
  • You shouldn't modify props and remove the data from the parent state instead Commented Jul 17, 2019 at 15:32
  • but If I want to modify it? how can this be done? Commented Jul 18, 2019 at 10:40

1 Answer 1

1

You need to concat from 0 to index - 1 and from index + 1 to length - 1. So a simple this.props.data.slice(0, index).concat(this.props.data.slice(index) + 1) Should work.

Imo concat is easier to read and reason about because it does not mutate your array.

A filter could also work for you:

 const filterIndex = target => (_, i) => i !== target;

 newData = data.filter(filterIndex(index));

To use the filter version is pretty easy, two ways, depending on the use case.

1) Remove a specific index without leaving holes in the array

const target = this.props.data.indexOf(oldData);
const newData = this.props.data.filter((_, index) => index !== target);

2) Remove a specific value from the array (all its occurrences) without leaving holes in the array

const newData = this.props.data.filter((data) => data !== oldData);

Those two are slightly different as the first one will only remove the first occurrence of oldData and the second all occurrences.

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

5 Comments

To understand the code should be like this. this.props.data.slice(0, this.props.data.indexOf(oldData) - 1).concat(this.props.data.slice(this.props.data.indexOf(oldData)) I tried and is not working.
my bad, off by one error. I would recommend using the filter version much more explicit than the slice concat stuff.
adz5A would you be able to show me how can I use your implementation with mine? by using props.
I updated my answer, let me know if it is clearer for you. Have a nice day.
Thanks fixed the problem, I added the value as a state and checked the nextProps, then set them up, if not matching, then implement your code. THanks

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.