21

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"]
trincot
  • 317,000
  • 35
  • 244
  • 286
borayeris
  • 2,603
  • 1
  • 27
  • 31
  • 2
    He probably wants to reindex the array, judging from his fiddle. – Alin Purcaru Jan 21 '11 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 Jan 21 '11 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 Jan 21 '11 at 14:18
  • @Alin. You are absolutely right. – borayeris Jan 21 '11 at 14:20

10 Answers10

39

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)
Redsandro
  • 11,060
  • 13
  • 76
  • 106
  • 7
    Note that it will return a new array without affecting `testArray`. You might want to redefine it: `testArray = testArray.filter(val => val);` – pmrotule Nov 04 '16 at 08: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 Nov 15 '16 at 11:18
  • 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)` – enriquejr99 Jun 08 '22 at 08: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;
  };
}
Exelian
  • 5,749
  • 1
  • 30
  • 49
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('|'))
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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

Hobbyist
  • 15,888
  • 9
  • 46
  • 98
Arron
  • 767
  • 8
  • 11
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);   
capdragon
  • 14,565
  • 24
  • 107
  • 153
2

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
2
testArray = testArray.filter(Boolean)

This should re-index your array.

Joe Foster
  • 31
  • 3
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

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

elasticrash
  • 1,181
  • 1
  • 12
  • 30
-1

Try This

var testArray=testArray.join(" ");
Wazy
  • 8,822
  • 10
  • 53
  • 98