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});
    }
}
cbass
  • 2,548
  • 2
  • 27
  • 39
Malek
  • 95
  • 1
  • 8
  • Possible duplicate of [How do I remove objects from a javascript associative array?](https://stackoverflow.com/questions/346021/how-do-i-remove-objects-from-a-javascript-associative-array) – Erik Terwan Jan 02 '19 at 15:02

3 Answers3

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 });
}
Chris
  • 6,331
  • 1
  • 21
  • 25
dan
  • 1,198
  • 8
  • 25
  • Make sure to include a polyfill for the “includes” function if you need to support older browsers like IE11 – Frank Jan 09 '19 at 21:35
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

  • `indexOf` does not take lmbda as parameter. Unless you want to find an index of a lambda in an array of lambdas. – Dmitry Jan 02 '19 at 15:12
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 });
}
Dmitry
  • 6,716
  • 14
  • 37
  • 39
  • 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 – Frank Jan 09 '19 at 21:40