Home > Software engineering >  slicing array list five elements at a time in javascript
slicing array list five elements at a time in javascript

Time:04-21

UPDATE: The below code does not work the way I wanted to, like as I mention below, it should show five items at a time when the user clicks on the button.

I'm trying to use javascript slice method (please suggest if this is not the right way to use), the array list show five array item at a time and I have created the codepen example to show what I'm trying to do

Let's assume I have 20 records, if the user click on first time, I should be getting 1-5 array items if the user click on second time, I should be getting 5-10 .....so on and so forth.

https://codepen.io/TLJens/pen/NPZyYR

The code here:

$('#loading').hide();

var counts = 0;
var displayCount = 5;
var starting = 0;
var data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];

function slicemydata(sstart, totalsize, eend) {  
    var items = []; debugger;
    if (totalsize <= data.length) {
        if (eend == 0) {
          items = data.slice(sstart,totalsize);
        } else { 
          if (sstart > eend) {
            eend = data.length;
          }
          items = data.slice(sstart, eend);
          sstart =  displayCount   5;
        }
    }
    console.log(items);
  $('.js-lazy-load-data').append(items);
}

$('.js-lazy-load').click(function () {
 
  counts  ;
  slicemydata(starting,data.length,displayCount);
 
    $('.js-lazy-load').fadeOut();
  
    // Minor timeout before showing loader
   // setTimeout(function () {
   //     $('#loading').fadeIn();
   // }, 400); 
  
    // Simulate server call by showing loading gif  
    // for 2.5 seconds before displaying results
    //setTimeout(function () {
    //    $('#loading').fadeOut();
    //}, 2600); 
  
    // Display results after 3 seconds
    setTimeout(function () {
        //$('.js-lazy-load-data').append(data);
        $('.js-lazy-load').show();
    }, 1000);  
});

CodePudding user response:

Here's how I would approach it.

  1. Pass in the data and the element that needs to be updated to a function.

  2. That function initialises the index, and returns a new function that acts as the handler for the listener.

  3. Within the body of that function you do the work of writing the new HTML using the sliced data, and then updating the element.

const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];

// Cache the elements
const div = document.querySelector('div');
const button = document.querySelector('button');

// Call `slicer` with the data, and the element to be updated.
// `slicer`returns a new function that is assigned to the listener
button.addEventListener('click', slicer(data, div), false);

// `slicer` accepts some data, and the 
// element to be updated
function slicer(data, div) {

  // Initialises the `index` which is
  // scoped to the returning function. No
  // need for global variables!
  let index = 0;

  // Returns a function that keeps a record
  // of index so it can update it
  return function () {

    if (index < data.length) {
      
      // `slice` the data from the current
      // index, `map` over that array to create
      // some HTML, and then join it up
      const html = data
        .slice(index, index   5)
        .map(el => `<span>${el}</span>`)
        .join(', ');

      // Add that to the element that needs updating
      div.innerHTML = `<div>${html}</div>`;
      
      // Finally increase the index
      index  = 5;
    
    } else {
    
      console.log('No more data');
    
    }
      
  }

}
<button>Click me!</button>
<div></div>

Additional documentation

CodePudding user response:

So I think if all you're wanting to do is paginate the data, you can do it much simpler by just keeping track of the current "pageIndex" you're on and how long each "page" is. That way, your start position in the array is just pageIndex * pageSize and your end position in the array is just start pageSize. Then all you have to do to get the next or previous page is just increment/decrement your page index accordingly. I'll leave the exercise of displaying the data to you since that's not relevant to what you needed help with. Hope this helps!

let data = [1,2,3,4,5,6,7,8,9,10,11,12,13];
let currentPage = 0;
let pageSize = 5;
function getPage(data, pageSize, pageIndex) {
  let start = pageSize * pageIndex;
  return data.slice(start, start   pageSize) 
}

console.log(getPage(data, pageSize, currentPage));
currentPage  ;
console.log(getPage(data, pageSize, currentPage));
currentPage  ;
console.log(getPage(data, pageSize, currentPage));
currentPage  ;
console.log(getPage(data, pageSize, currentPage));
currentPage  ;

CodePudding user response:

This might be a use case for Generators and generator functions; the OP's task at least makes a good practical exercise ...

function* createPaginator(itemList = [], pageItemCount = 1, pageNumber = 0) {
  pageItemCount = Math.max(pageItemCount, 1);

  while (itemList.length >= 1) {
      pageNumber;

    yield {
      pageNumber,
      itemList: itemList.splice(0, pageItemCount),
    };
  }
}


let paginator = createPaginator(
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 5
);
let pagination;

console.log('...automatically tiggered `next` based iteration...');

while (pagination = paginator.next().value) {
  const { pageNumber, itemList } = pagination;

  console.log({ pageNumber, itemList });
}


paginator = createPaginator(
  [1, 2, 3, 4, 5, 6, 7, 8], 6
);
console.log('...explicitly (e.g. event) triggered `next` based iteration...');
console.log(
  paginator.next()
);
console.log(
  paginator.next()
);
console.log(
  paginator.next()
);
console.log(
  paginator.next()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

The below DOM / DOM event implementation demonstrates the handy usage of a generator based paginator/pagination.

function* createPaginator(itemList = [], pageItemCount = 1, pageNumber = 0) {
  pageItemCount = Math.max(pageItemCount, 1);

  while (itemList.length >= 1) {
      pageNumber;

    yield {
      pageNumber,
      itemList: itemList.splice(0, pageItemCount),
    };
  }
}

function handlePaginationFromBoundData({ currentTarget }) {
  const { paginator, elmOutput } = this;
  const pagination = paginator.next().value ?? null;
  
  if (pagination !== null) {
    const { pageNumber: page, itemList: items } = pagination;

    elmOutput.value = `... page: ${ page }, items: ${ items } ...`;
  } else {
    elmOutput.value = '... no more pages / page items ...';

    currentTarget.disabled = true;
  }
}
document
  .querySelector('button')
  .addEventListener(
    'click',
    handlePaginationFromBoundData.bind({
      paginator: createPaginator(
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 5
      ),
      elmOutput: document.querySelector('output'),
    })
  );
<button>paginator</button>
=>
<output>...</output>

  • Related