0

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

7
  • not working is not a good problem description. Please explain the problem with the actual output and expected output. Commented Jun 27, 2015 at 6:42
  • when i increment say, click on next i am getting next batch of slices from the array. when click prev button i am not getting previous batch of slices, please see the console for output. Commented Jun 27, 2015 at 6:43
  • I want get the slice by each 2 by increment or decrement of the buttons. Commented Jun 27, 2015 at 6:45
  • What should happen around the edges, for example after 8, when I press Next? Commented Jun 27, 2015 at 6:46
  • see the result, it's like circular output. you will get again from the start. in my try, again the array is not properly starting from start index. sorry for that - if you have any good solution let me know. Commented Jun 27, 2015 at 6:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Technically speaking, % is not a modulo operator, it is a remainder operator. There has been talk of adding a true modulo operator to JavaScript in the future though.
Ah, true enough. Edited answer to reflect that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.