1

I was wondering how to do the follow.

I have an array of objects and I'm trying to retrieve a set amount eg of them around a given index.

Here's an example.

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

If the index is 0 I want [0 - 4]
If the index is 4 I want [2 - 6]
If the index is 9 I want [6 - 10]

But I also want it to work if the array is smaller then the max too. Eg

var arr = [0,1,2];
var index = 0;
var max = 5;

Any index would return [0 - 2]

Any thoughts?

2
  • The second one should return 0-3 although there's only 0-2 in the array? How should this work? Will it guess? Commented May 13, 2012 at 8:26
  • Sorry my mistake, it should return 0 - 2 Commented May 13, 2012 at 8:28

2 Answers 2

4

You might want to try this

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

function getRange(array, index, range) {
    var least = index - Math.floor(range/2);
    least = (least < 0) ? 0 : least;
    return array.slice(least, least+range);
}
Sign up to request clarification or add additional context in comments.

Comments

0
var start = index - max / 2;
if (start < 0) start = 0;
var end = start + max;
if (end > arr.length) {
  end = arr.length;
  start = end - max;
  if (start < 0) start = 0;
}
var result = arr.slice(start, end);

3 Comments

Thanks for the reply, Riateche. I have tried slice. My problem is that I want the index to appear in the middle of the range. So if I have an index of 2 I should get the two results to the left and two to the right where possible. But I always want 5 results where possible too.
this only goes forward from the index, not backwards
You may also want to check if index + max > arr.length, in order to fulfill this wish: If the index is 9 I want [6 - 10]

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.