Search code examples
arraysfunctionreactjsarrayobjectarray-key

Get array key to remove an array based on that array object


New question, so this is the array

[
    0: {
        "id" : "3"
        "name": "David",
        "age": "20"
    },
    1: {
        "id" : "6"
        "name": "",
        "age": "18"
    },
    2: {
        "id" : "8"
        "name": "Micheal",
        "age": "25"
    },
    3: {
        "id" : "9"
        "name": "Wonder Women",
        "age": "20"
    },
    4: {
        "id" : "12"
        "name": "Clark",
        "age": ""
    }
]

How to delete based on id when I click a button? In my app have a delete button to delete this array. I think it need to get array key in order to delete the array.

For example: I can get the id=8, but how can i get array key 2 to delete number 2 array?

If you don't understand, please welcome to comment. Thanks.


Solution

  • if you want to directly manipulate the contents of an array instead of returning new array, you can try this

    let index = array.findIndex(obj => obj.id == objIdToDelete)
    if(index != -1) { array.splice(index, 1) }
    

    check Array.prototype.splice() to know more