GibboK
GibboK

Reputation: 73918

JS working with two array

I need to create an array cells as described in my comment. I would like to know what is wrong with this script, and the more perfomant way to achieve this result.

Look at the js fiddle http://jsfiddle.net/XvTrf/5/

var data = ['D-0','D-1','D-2','D-3','D-4','D-5','D-6','D-7','D-8','D-9'];

var cells=[];
var d = 0, lenD = data.length;

while(d< lenD){
    if(d === 1 || d === 5 || d ===6){
       cells.push('test');
    }else {
        cells.push(data[d]);
    }
    d++;
}
console.log(cells);


/* result wanted
D-0
test
D-1
D-2
D-3
test
test
D-4
D-5
D-6
D-7
D-8
D-9

*/

Upvotes: 0

Views: 64

Answers (1)

Menelaos
Menelaos

Reputation: 25725

The else statement means that some entries are not being entered.

Additionally, you could make use of the splice method... this will result in less code but also less speed.

var data = ['D-0','D-1','D-2','D-3','D-4','D-5','D-6','D-7','D-8','D-9'];

var cells= data.slice(0);;
cells.splice(1, 0, "TEST");
cells.splice(5, 0, "TEST");
cells.splice(6, 0, "TEST");
console.log(cells);

alert(cells);

If you want to see the difference in speed:

http://jsfiddle.net/DBhPB/1/

Update

A faster solution is to pre-allocate your array size, instead of using the push method.

var data = ['D-0', 'D-1', 'D-2', 'D-3', 'D-4', 'D-5', 'D-6', 'D-7', 'D-8', 'D-9'];

var cells = new Array(data.length + 3);

var d = 0,
    insertions = 0,
    lenD = cells.length;


while (d < lenD) {

    if (d === 1 || d === 5 || d === 6) {
        cells[d] = 'test';
        insertions++;
        d++;
    }
    else
     {
     cells[d] = data[d-insertions];
     d++;
     }    
}

alert(cells);

Upvotes: 2

Related Questions