I have a code :
myarray[150] = 'a';
myarray[80] = 'b';
myarray[122] = 'c';
And then :
myarray.splice(80, 1);
myarray[80] = 'b';
The result of my code above on my application is :
[150] = 'a'; [80] = 'b'; [121] = 'c';
I don't understand why c
value have 121
as index. Can anyonen explain what's wrong with my code?
I have a code :
myarray[150] = 'a';
myarray[80] = 'b';
myarray[122] = 'c';
And then :
myarray.splice(80, 1);
myarray[80] = 'b';
The result of my code above on my application is :
[150] = 'a'; [80] = 'b'; [121] = 'c';
I don't understand why c
value have 121
as index. Can anyonen explain what's wrong with my code?
- 3 Don't use sparse arrays, there is always a better data structure than a sparse array. Use an object (e.g. dictionary), or an array of objects. – Adam Jenkins Commented Jan 31, 2017 at 17:32
- @adam : can you give example? – Mr. Mike Commented Jan 31, 2017 at 17:35
-
1
myarray = {150:'a',80:'b',122:'c'}
In this case, simply dodelete myarray[80]
(ormyarray[80] = null
). An alternative data structure is an array of objects:myarray = []; myarray.push({id:150,value:'a'}),myarray.push({id:80,value:'b'}),myarray.push({id:122,value:'c'})
– Adam Jenkins Commented Jan 31, 2017 at 17:36 - 2 @Michael not quite right. Both are using delete, but Adams point is to not use an Array but an Object, wich mike isnt suggesting – Jonas Wilms Commented Jan 31, 2017 at 17:40
- 2 Back to my original ment - don't use a sparse array. – Adam Jenkins Commented Jan 31, 2017 at 17:41
6 Answers
Reset to default 6This line of code removes one element of the array at index 80. Thus, all elements after 80 would be shifted down one index:
myarray.splice(80, 1);
You have to use:
delete myarray[80]
for safe delete
You want to use splice twice:
myarray.splice(80, 1);
myarray.splice(80, 0,"b");
Or you dont remove, but override to null/undefined
myarray[80]=undefined;
However this array will consist of 117 "undefined" wich is, as adam stated an antipattern. May do this:
var myarray={};
myarray[80]="b";
delete myarray[80];
It has just one element, and is therefore not memory consuming.
Because When you initiated c on index 122, and then removed one element fron your array, Its length changed and the latest index is now 121 not 122
As the Array.prototype.splice()
documentation specifies, the second parameter is the number of elements to be deleted.
Thus, when doing
myarray.splice(80, 1);
You are only removing one element, at position 80.
"c"
gets moved one index to the left.
Furthermore, doing
myarray[80] = 'b';
does not add another element, but changes the value of an already existing one.
.splice() removes an array element, but does not make it empty. Therefore, the index change and 'c' has an index of '121'
More about it you can read here