Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove JavaScript array element and reset keys

Tags:

javascript

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

like image 304
Emeka Mbah Avatar asked Jul 10 '16 20:07

Emeka Mbah


People also ask

Can we delete array element in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How do I remove a specific element from an array?

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.

How do you remove an element from an array at a specific index JavaScript?

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.


1 Answers

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. 
like image 169
Yasin Yaqoobi Avatar answered Oct 11 '22 04:10

Yasin Yaqoobi