Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove value from js array without reordering keys

Tags:

javascript

I have an array, and I want to remove just one element, but without reordering keys. Is there an easy way without using delete or rebuilding the entire array?

Or alternatively clean up after delete to get rid of the undefined values, fixing the length again.

var array = ["valueone", "valuetwo"];

console.dir(array); // keys 0 and 1
array.splice(0, 1);
console.dir(array); // key 1 is now 0, do not want!
like image 997
Nuoun Avatar asked Dec 26 '22 08:12

Nuoun


1 Answers

You can delete the elements of an array:

a = ['one', 'two'];
delete a[0];

// a is now [undefined, 'two'];

alternatively, set a[0] explicitly to undefined.

Note that an arrays .length parameter is automatically maintained by the system. If you intentionally set it to a higher number, you'll just get a whole load of undefined values for the missing keys:

a.length = 10;
// a is now [undefined, 'two', undefined x 8]

If these semantics are not acceptable to you, then you should consider using an Object instead. This will preserve your keys, and perhaps be more efficient, but you lose the .length property.

like image 69
Alnitak Avatar answered Jan 07 '23 02:01

Alnitak