Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an element from a sparse array?

Tags:

javascript

I want to know the right way to delete an element in sparse array but keep the indices of others the same.

I don't want to use splice as it'd change the indexes of values.

like image 386
user5858 Avatar asked Jan 29 '26 22:01

user5858


1 Answers

You could take the delete operator and remove the item. The place is now sparse.

var array = [, , 1, 2, 3];

console.log(array);

delete array[3];

console.log(array);

array.forEach(v => console.log(v)); // shows two elements
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 74
Nina Scholz Avatar answered Feb 01 '26 11:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!