Search code examples
javascript

How to remove JavaScript array element and reset keys


I have an array like below:

 var fields = [
    {name:"mark", age:"23"}, 
    {name:"smith", age:"28"}, 
    {name:"kelvin", age:"25"}, 
    {name:"micheal", age:"22"}
];

I understand that fields will now have index/keys 0,1,2,3

How do I delete index 2 and reset keys so that we now have 0,1,2 instead of 0,1,3


Solution

  • If I understand this correctly, you want to remove the array element at index 2 and re-index the array so that there is no empty space. If that's the case, JavaScript has got you covered.

    This will modify your original array and will remove only one element starting at index 2.

    fields.splice(2,1);
    

    MDN Reference