javascript - Get the N elements from array based on the position -


i want function returns sub array takes position & no. of elements want. think there may algorithm find pivot point or & can sub array, totally forgot it.

example: = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] want 6 elements if position = 0, want [1, 2, 3, 4, 5, 6] if position = 1, [1, 2, 3, 4, 5, 6] if position = 2, [1, 2, 3, 4, 5, 6] if position = 3, [1, 2, 3, 4, 5, 6] if position = 4, [2, 3, 4, 5, 6, 7] if position = 5, [3, 4, 5, 6, 7, 8] if position = 6, [4, 5, 6, 7, 8, 9] if position = 7, [5, 6, 7, 8, 9, 10] if position = 8, [5, 6, 7, 8, 9, 10] if position = 9, [5, 6, 7, 8, 9, 10] middle of n elements based on position pass. 

i can write own loop contain multiple if-else conditions done. feel there may easy way it.

i didnt include incomplete code snippet because feel there must algorithm this.

what want : array.prototype.slice(...)

it's neatly documented here : https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/slice

var n = 6; var start = math.max(0, math.min(math.floor(position-n/2), a.length-n)); return a.slice(start, start+n); 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -