Delete vs splice on associative array

sarsnake picture sarsnake · Nov 17, 2011 · Viewed 36.7k times · Source

If I have a JS associative array which is from what I gather is really an object, and I wish to remove an element, using delete myArr[someId] will set the element to undefined, whilst splice won't work at all... so what is the alternative for an associative array if I wish to delete an element (rather than setting it to undefined)

Answer

Geuis picture Geuis · Nov 17, 2011

The terminology in js can be confusing at first, so lets straighten that out.

Yes, pretty much everything in js is an object. However, there are differences in the data types.

An array can be used like as associative array, but it's different than an object literal.

var x = []; //array
var y = {}; //object literal

An array is like a list. The keys of an array can be a numerical index or a string.

var x = ['a','b']; // x[0] === 'a', x[1] === 'b';
var x = [];
    x['one'] = 'a';
    x['blah'] = 'b'; 

Object literals are like dictionaries. They can be used in a similar way.

var x = { 0: 'a', 1: 'b' };
var x = { one: 'a', two: 'b' };

However, this is where you need to understand the differences.

You can use an array like an object literal, but you can't use an object literal quite like an array.

Arrays have the automated "length" property, that increments and decrements automatically based on the total number of elements in the array. You don't get this with object literals. Arrays also get all of the other array-specific methods like shift, unshift, splice, pop, push, etc. Object literals don't have those methods.

Let's talk about delete and what happens on an array and on an object literal.

var x = ['a', 'b']; //["a", "b"]
delete x[0]; //[undefined, "b"]

var x = {0:'1', 1:'b'}// { 0:"1", 1:"b"}
delete x[0]; // { 1:"b" }

If you perform a delete on an element of an array, the length of the array doesn't change. The element index is preserved and the value is set to 'undefined';

Conversely, performing a delete on an object literal removes the key/value from the object.

Finally, if you want to remove an element from an array.

var x = ['a', 'b']; 
x.splice(0,1); //modifies x. ['b']

So, in summary use delete on object literals. Use splice on arrays.

Hope this helps.