HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Adding a bulk of items in the middle of a sparse array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thearraybulkaddingitemssparsemiddle

Problem

I'd like to add a bulk of items into a sparse array, starting at a certain index.
I came along this requirement in order to accomplish client side pagination while not retrieving all data from server (assuming server returns the right data, given the required indexes).

To keep right indexes when "Skipping" and "Taking", I need to store the items in a sparse array. Besides relevant indexes, other places in array might as well be undefined.

I wrote the following snippet of code, assuming bulk is the retrieved chunk of items from Server, and index is where the first item should be placed.

items = new Array(totalItemsPossibleCount);
    items = items.slice(-index)
                 .concat(bulk)
                 .concat(items.slice(index+bulk.length));


  • Is there a shorter way to do so?



  • Can this be achieved with underscore.js in more readable way?

Solution

You don't need to worry about sparse arrays in JavaScript and there is no need to instantiate with the Array constructor. If you insert into a random index then the rest of the array is just padded with undefined references:

var items = [];
items[5] = 'foo';
console.log(items); // [5: "foo"]
items.toString();   // ",,,,,foo"


To add new items into the middle of an array you can use the splice function:

items.splice(index, 0, bulk);


The index is where to start adding items, 0 is how many items to remove after that point, and bulk is the new items to add at that point. Splice acts on the array directly, and returns any items that were removed.

Code Snippets

var items = [];
items[5] = 'foo';
console.log(items); // [5: "foo"]
items.toString();   // ",,,,,foo"
items.splice(index, 0, bulk);

Context

StackExchange Code Review Q#46446, answer score: 4

Revisions (0)

No revisions yet.