23

Here is my example.

Can you tell me how can I make the array have consecutive keys? I want to reindex my array.

Currently I have:

var testArray = new Array();
testArray[3]="qwerty";
testArray[7]="asdfgh";
testArray[13]="zxcvbn";

console.log(testArray);

But I'd like to get the values at indices 0, 1 and 2 (and so on):

["qwerty", "asdfgh", "zxcvbn"]
4
  • 2
    He probably wants to reindex the array, judging from his fiddle.
    – Alin P.
    Commented Jan 21, 2011 at 14:15
  • @warren; in my example array keys are 3, 7, 13. When I serialized them it became ",,,qwerty,,,,asdfgh,,,,,,zxcvbn". What I want is "qwerty,asdfgh,zxcvbn".
    – borayeris
    Commented Jan 21, 2011 at 14:16
  • you're just missing what to join the array with. Having nothing in your .join() will result in the commas. you need at least single quotes (.join('')), but that will put the results right next to each other
    – hellatan
    Commented Jan 21, 2011 at 14:18
  • @Alin. You are absolutely right.
    – borayeris
    Commented Jan 21, 2011 at 14:20

10 Answers 10

40

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)
3
  • 7
    Note that it will return a new array without affecting testArray. You might want to redefine it: testArray = testArray.filter(val => val);
    – pmrotule
    Commented Nov 4, 2016 at 8:56
  • @pmrotule if you want to keep it around, yes. Following the example in the question, shortest would be var testString = testArray.filter(val => val).join();
    – Redsandro
    Commented Nov 15, 2016 at 11:18
  • 1
    This answer is wrong. Filter expects the callback to return true or false. If your array has falsy values such as null or false they will be removed too. You should always return true such as testArray = testArray.filter(val => true) Commented Jun 8, 2022 at 8:33
8

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;
  };
}
0
6

You could filter the array by using a callback which returns true or other truthy value, because Array#filter omits sparse elements.

If Boolean is taken, the result filters not only sparse items, but items which have a falsy value. To prevent this, take a callback which returns true for every element.

array.filter(_ => true);

var array = [];

array[10] = 0;
array[20] = 0;
array[30] = 0;

console.log(array.filter(_ => true).join('|'))

5

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

1
  • Uncaught ReferenceError: i is not defined
    – fdrv
    Commented Mar 16, 2016 at 23:17
4

To reindex an array, use Object.values:

var sparseArray = new Array();
sparseArray[3] = "qwerty";
sparseArray[7] = "asdfgh";
sparseArray[13] = "zxcvbn";

let result = Object.values(sparseArray);
console.log(result);

1
  • How come this isn't the accepted answer, or at least upvoted? Commented Dec 7, 2021 at 21:06
2
var testArray = new Array();
testArray[3] = "qwerty";
testArray[7] = "asdfgh";
testArray[13] = "zxcvbn";


var isEmpty = function(x) {
   // returns true if x is null and false if it is not.
    if(x!=null){ 
        return true;
    }else{ 
        return false
    } 
}
var newArray=testArray.filter(isEmpty);

var testString2 = newArray.join();

$('#write').text(testString2);   
2
testArray = testArray.filter(Boolean)

This should re-index your array.

1

Maybe this is simpler to solve the problem:

var j=0;
var tmpTab=[];
    
for(var i in origTab) {
 tmpTab[j]=origTab[i];
 ++j;
}
origTab=tmpTab;
delete tmpTab;
0
0

you mean without the commas? if so just do this var testString = testArray.join(""); or you can add any char you want between.

3
  • 1
    What I need is re-indexing the array. Not this.
    – borayeris
    Commented Jan 21, 2011 at 14:30
  • you could always just join the Array and then resplit it with a certain delimiter. Maybe its not that pro but its 2 lines of code. Commented Jan 23, 2011 at 10:19
  • joining and re-splitting will not work if array elements are objects, for example Commented Nov 30, 2013 at 19:17
-1

Try This

var testArray=testArray.join(" ");
1
  • 1
    What I need is re-indexing the array. Not this.
    – borayeris
    Commented Jan 21, 2011 at 14:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.