Dylan Mac
Dylan Mac

Reputation: 75

how to remove an object within an array using the object's index

so I created an array with several objects inside it

const students = [
    {jean:14},
    {mike:19},
    {nean:16},
    {annie:17}
]

and I want to remove certain object from the array by using the object's index

let index = students.findIndex(i => {
    if (Object.keys(i) == 'nean'){
        return true
    }
})

and it returns the index of the object that I want to remove from the array and I do .splice() to remove it from the array. It does remove the object that I expect to be removed but it also removes the item after it

    students.splice(index, index)
    console.log(students) 

//(2) […] 0: Object { jean: 14 } 1: Object { mike: 19 } length: 2

Upvotes: 1

Views: 1411

Answers (2)

Alisa kh
Alisa kh

Reputation: 93

Array.splice() should be provided at least 2 arguments and from argument 3 to infinity are optional,

the first argument is the index where u want to start your manipulation, the second argument is the number of items that you would like to be deleted from that index onwards, and the third argument is the string/object that you would like to add

in your example you would like to start at the index that you have found using this function:


    let index = students.findIndex(i => {
        if (Object.keys(i) == 'nean'){
            return true
        }
    })

and you would like to delete just one! so you need to provide 1 for the second argument and not index,

js students.splice(index, 1)

as you don't need to add anything you will not provide the 3rd argument,

I hope this helps with all your array splice needs, good luck

Upvotes: -1

user15672038
user15672038

Reputation:

When using splice, the first argument is the index and the second is how many elements to remove from that index. so in order to remove just that element, you can do: students.splice(index, 1) reference: splice

Upvotes: 3

Related Questions