Skip to content Skip to sidebar Skip to footer

Javascript: Is There A Better Way To Retain Your Array But Efficiently Concat Or Replace Items?

I am looking for the best way to replace or add to elements of an array without deleting the original reference. Here is the set up: var a = [], b = [], c, i, obj; for ( i = 0; i

Solution 1:

Probably that the most comprehensive way yet still efficient would be to use push.

var source = [],
    newItems = [1, 2, 3];

source.push.apply(source, newItems);

If you ever reach the maximum call stack, you could seperate the operation into multiple batches.

var source = [],
    newItems = newArray(500000),
    i = 0,
    len = newItems.length,
    batch;

for (; i < len; i++) newItems[i] = i;

//You need to find a real cross-browser stack size, here I just used 50kwhile((batch = newItems.splice(0, 50000)).length) {
    source.push.apply(source, batch);
}

console.log(source[499999]);

Also keep in mind that expensive operations might hang the browser, especially in old browsers that have slow JS engines. To circumvent the issue, you could further split the process into smaller batches and let the browser breath by using setTimeout.

Finally another approach I thought of would be to use a wrapper object around your array which would allow you to replace the array directly since your references would be retained through the object.

var arrWrapper = { list: [] },
    obj1 = { items: arrWrapper },
    obj2 = { items: arrWrapper };

//update the array
obj2.items.list = [1, 2, 3, 4];

//access the array
obj1.items.list;

The only restriction would be to avoid keeping a reference to arrWrapper.list directly.

Note: If you are targetting modern browsers only, you could probably make use of WebWorkers. However as far as I know, you can only pass serialized data which means that the worker wouldn't be able to modify the source array directly.

Post a Comment for "Javascript: Is There A Better Way To Retain Your Array But Efficiently Concat Or Replace Items?"