kfirba
kfirba

Reputation: 5441

Javascript: Replacing items in array with another set of items

I have an app where I fetch some data from my server and keep it in an array. When I display it I want to display it paginated so I decided to have 50 items per page.

I want to implement a refresh functionality so I can refresh the current viewed page. For example, if I've loaded 3 pages already, which means I have 150 items in my array, and I refresh page 2 (which means I fetch items 50-99 from my server) I want to replace the current items with the new items.

Basically what I want to do is to remove items 50-99 in my current array and insert "new" 50 items to the current array starting at index 50.

I tried doing so with:

// remove the items
items.splice((this.currentPage*50 -50), 50)

// add the new freshly grabbed items instead
Array.prototype.splice.apply(
    items,
    [(this.currentPage*50 -1), data.data.length].concat(data.data));

But it does seem to work kinda buggy. If I have only 1 page loaded then it works as expected. It deletes all of the 50 items and replaces them with the new items. However, if I have 2 pages loaded and I try to refresh page 1 I can suddenly see that the current items array length is 99 instead of 100. I tried playing with that but I just can't get it work :/

Any idea how I can efficiently delete a set of items from my array based on the current refreshed page and replace the deleted items with the new array that has the new items?

Upvotes: 1

Views: 94

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

I think, you do not need this.

// remove the items
items.splice((this.currentPage*50 -50), 50)

otherwise you need to implement a 0 for the length like this:

// add the new freshly grabbed items instead
Array.prototype.splice.apply(
    items,
    [(this.currentPage - 1) * 50, 0].concat(data.data));
    //                            ^

The best thing, is to do it in one step like this:

var a = Array.apply(null, { length: 150 }).map(function (_, i) { return i; }),
    b = Array.apply(null, { length: 50 }).map(function (_, i) { return i + 1050; });

Array.prototype.splice.apply(a, [50, b.length].concat(b));            
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');

Upvotes: 2

Related Questions