Javascript - Reindexing an array
Array.prototype.filter()
is not executed on deleted or previously undefined items. So you can simply do:
testArray.filter(function(val){return val});
..in order to re-index your array.
Or ES6:
testArray.filter(val => val)
If you don't mind using javascript 1.6: (note: this code uses the jQUery library)
var testArray = new Array();
testArray[3]="qwerty";
testArray[7]="asdfgh";
testArray[13]="zxcvbn";
var testString = testArray.filter(function (item) { return item != undefined }).join();
$(function(){
$('#write').text(testString);
});
filter prototype:
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
Super simple function:
function reindex_array_keys(array, start){
var temp = [];
start = typeof start == 'undefined' ? 0 : start;
start = typeof start != 'number' ? 0 : start;
for(var i in array){
temp[start++] = array[i];
}
return temp;
}
testArray = reindex_array_keys(testArray);
Note: this will blow away any custom keys. the result will always be numerically indexed. you could add in checks for if it's an array or not but i tend to just not use functions i build other than they are intended to be used. you can also start the index higher if you like:
testArray = reindex_array_keys(testArray, 3);
which will produce 3 'undefined' items at the beginning of the array. you can then add to it later but i think it would be better to do testArray.unshift('newValue')
first then reindex personally.
have fun