bier hier
bier hier

Reputation: 22550

How to return the next x amount of items in an array?

I have an array of objects in js:

[{name:'John',number:1},{name:'Peter',number:2},{name:'Mario',number:3},{name:'Jack',number:4}]

Trying to create a pagination component and wondering how to select the next couple of objects. I tried slice but could not get it to work. So for example :

SelectPage(1) would return nr 3 and 4, SelectPage(0) nr 1 and 2 etc

Is there a lodash function for this?

Upvotes: 0

Views: 64

Answers (2)

Akaahn
Akaahn

Reputation: 36

Something along the lines of this?

var list = [{name:'John',number:1},{name:'Peter',number:2},{name:'Mario',number:3},{name:'Jack',number:4},{name:'Mario',number:5},{name:'Jack',number:6}]

function SelectPage(list, index, pageSize) {
    return list.slice(index*pageSize, index*pageSize+pageSize)
}

Updated with improvement, thanks @nnnnnn

Upvotes: 2

Etherealm
Etherealm

Reputation: 2484

Here's a sample code to get you running, you can modify it as per your requirement.

// Your dummy data

 var data = [
  {name:'John',number:1},
  {name:'Peter',number:2},
  {name:'Mario',number:3},
  {name:'Jack',number:4}
 ];

// function for pagination

  function page(index,data){
  var count = 2;
  var pageNo = index;
  if(index == 0){
    pageNo = 1;
  }
  var currentCount = count * pageNo;

  return (data.slice(index,currentCount));
}

// call this function and pass page index and the data

page(0,data); // 1st page and data array

Upvotes: 0

Related Questions