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
Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove.
If I am understanding this correctly you want to remove array element at index 2 and re-index the array so there is no empty space. If that's the case javascript has got you covered.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
fields.splice(2,1); // This modifies your original array and removes only one element starting at index 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With