iLemming
iLemming

Reputation: 36176

Fastest way to determine offset in array

If I have an array of arbitrary length. How can I find what offset for a given element of that array would be if number of elements per slice is known? I mean without actually slicing the array.

Example:

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..n]

if perSlice = 4; offset for arr[5] == 1, for arr[8] == 2 etc.
if perSlice = 3; offset for arr[2] = 0, for arr[4] = 1 etc.

i.e.: 

perSlice = 4
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..n]
 0  0  0  0  1  1  1  1  2  2  2,  ..n

Upvotes: 0

Views: 464

Answers (3)

AlexanderBrevig
AlexanderBrevig

Reputation: 1987

Find the offset at index i by doing: parseInt(i/perSlice)

var arr = [0,1,2,3,4,5,6,7,8,9,10];

function getIndexes(arry, perSlice) {
  var ret =[];
  for(i in arry){
    ret.push(parseInt(i/perSlice));
  }
  return ret;
}

var indexes = getIndexes(arr, 4);
console.log(indexes);

EDIT: Note this uses the value at index i, not the index itself. Code is easily modifiable to use index instead of value.

Upvotes: 1

folkol
folkol

Reputation: 4883

You can use indexOf, and take that modulo "perSlice"

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..n]
var perSlice = 4;
arr.indexOf(5) % perSlice

If you want to know WHICH slice the element ends up in, divide instead of %.

Math.floor(arr.indexOf(5) / perSlice) // 1

Upvotes: 3

munsifali
munsifali

Reputation: 1731

Use the modulus operator

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..n]

       arr[(((index + step) % arr.length) + arr.length) % arr.length];

Upvotes: 0

Related Questions