1

I want to remove a specific element from an array, I am getting the key of the element from the input. I want to be able to remove the element only by knowing the key.

This is the array:

state ={
    splitAmount : [{
        "SplitAmount0": this.props.data.amount1
    }, {
        "SplitAmount1": this.props.data.amount2
    }, {
        "SplitAmount2": this.props.data.amount3
    }]
}

Remove function:

  removeSplitAmount(e) {
    console.log("remove",e.target.name)
    let array = [...this.state.splitAmount];
    let  index = this.state.splitAmount.IndexOf(p => p == e.target.name )
    if (index !== -1) {
        array.splice(index, 1);
        this.setState({splitAmount: array});
    }
}
1

3 Answers 3

2

You can use the .filter method on the array combined with the Object.keys to clean the function up a lot:

removeSplitAmount(e) {
    const newSplitAmount = this.state.splitAmount
      .filter(p => !Object.keys(p).includes(e.target.name));

    this.setState({ splitAmount: newSplitAmount });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Make sure to include a polyfill for the “includes” function if you need to support older browsers like IE11
1

You can use hasOwnProperty to filter objects you need.

removeSplitAmount(e) {
  const newSplitAmount = this.state.splitAmount
    .filter(x => !x.hasOwnProperty(e.target.name));

  this.setState({ splitAmount: newSplitAmount });
}

1 Comment

I think this is the best answer even though the “newSplitAmount” variable is not even necessary and could be removed if you want even less code
1

As Dmitry said you can't do a indexOf on an array of objects... i felt bad i didn't realize that. Would be useful on this case: var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

beasts.indexOf('bison')

On your case you are better to go with the .filter method as said in above answers because you are searching for and object with a specific property

1 Comment

indexOf does not take lmbda as parameter. Unless you want to find an index of a lambda in an array of lambdas.

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.