3gwebtrain
3gwebtrain

Reputation: 15303

How to get batch of array value from an array by incremental or decrements values

I have an array, It contains bunch of values in it. I would like to slice the array by increasing value of the count number or decreasing value of the count.

the count is updated by next and prev buttons. when user click on next the count increase and the user click on prev button the count decrease. using this wan to slice array values by my batch numbers.

here is my try:

var arr = [1,2,3,4,5,6,7,8,9];
var batch = 2;
var num = 2;
var total = arr.length;
var group = arr.slice(0, (batch % total));


var add = function (amount) {
     num = (num + total - 1 + amount) % total + (2)
     console.log(arr.slice((num-batch), (num % total)))
}

$('a').click(function (e) {
    var num = e.target.className == 'prev' ? -1 : 1;
    add(num);
})

console.log(group)

Live Demo

Upvotes: 0

Views: 872

Answers (1)

Grinde
Grinde

Reputation: 326

Assuming you're always looking for groupings of size batch, and want to wrap around your array, you could do something like this.

var add = function (amount) {
    num = ((num + batch * amount) % total + total) % total;

    var out = arr.slice(num, num + batch);
    if (out.length < batch) {
        out = out.concat( arr.slice(0, batch - out.length ) );
    }

    console.log(out);
}

Note that JavaScript % is not a modulo operator like in most languages, it is instead a remainder operator. Instead of putting you into the range [0, m - 1] it goes to the range [-m + 1, m - 1] while preserving sign (ie -6 % 5 = -1). An easy way to implement a true modulo is by doing doing ((n % m) + m) % m.

Upvotes: 2

Related Questions