Julius Doan Julius Doan - 5 months ago 10
Javascript Question

Shifting array of elements into another index of the array

Not sure if this may be a duplicate, but I am having some troubles trying to think of the best way of shifting an element in an array filled of arrays of elements.

Such as:

var foo = [
[ {obj: 1}, {obj: 2}, {obj: 3}, {obj: 4} ],
[ {obj: 5}, {obj: 6}, {obj: 7}, {obj: 8} ],
[ {obj: 9}, {obj: 10}, {obj: 11}, {obj: 12} ]
];


If I remove one element given an arrayIndex, it would remove that element then shift all of the proceeding elements down to the appropriate array. Such as if I remove obj 3 the result would be:

var arrayIndex = 0;
var objIndex = 2;

var bar = foo[arrayIndex].splice(objIndex, 1);


Result:

bar = [
[ {obj: 1}, {obj: 2}, {obj: 4}, {obj: 5} ],
[ {obj: 6}, {obj: 7}, {obj: 8}, {obj: 9} ],
[ {obj: 10}, {obj: 11}, {obj: 12} ]
];


Another example would be as shown removing obj 8:

var arrayIndex = 1;
var objIndex = 3;

var bar = foo[arrayIndex].splice(objIndex, 1);


Result:

bar = [
[ {obj: 1}, {obj: 2}, {obj: 3}, {obj: 4} ],
[ {obj: 5}, {obj: 6}, {obj: 7}, {obj: 9} ],
[ {obj: 10}, {obj: 11}, {obj: 12} ]
];


The issue for me is shifting all of the proceeding elements into the correct array position. Additionally, I would like the empty array to be removed. Where foo's length would decrease. foo will also be mutated.

Here was my attempted jsfiddle: https://jsfiddle.net/mLw8kncn/1/

Any help would be appreciated.

Answer

A simple way is to store your items in 1D array instead of 2D. Then manipulation the indexes.

var foo = [ {obj: 1}, {obj: 2}, {obj: 3}, {obj: 4},
    {obj: 5}, {obj: 6}, {obj: 7}, {obj: 8},
    {obj: 9}, {obj: 10}, {obj: 11}, {obj: 12} ];

function remove(arrayIndex, objIndex) {
    var realIndex = arrayIndex * 4 + objIndex;
    foo.splice(realIndex, 1);
}

Otherwise, you have to rearrange items after every splice.

function remove(arrayIndex, objIndex) {
    foo[arrayIndex].splice(objIndex, 1);

    for (var i = arrayIndex + 1; i < foo.length; i++) {
        var obj = foo[i].shift();
        foo[i - 1].push(obj);
    }

    if (foo[foo.length - 1].length <= 0) {
        foo.pop();
    }
}

And this is much complicated.

Comments