2016-11-10 60 views
2

我想要一个返回子阵列的函数,它需要一个位置&否。我想要的元素。我认为可能有一些算法来找到支点或&从我可以得到的子数组,但我完全忘了它。基于位置获取阵列中的N个元素

Example: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
I want 6 elements 
if position = 0, then I want [1, 2, 3, 4, 5, 6] 
if position = 1, then [1, 2, 3, 4, 5, 6] 
if position = 2, then [1, 2, 3, 4, 5, 6] 
if position = 3, then [1, 2, 3, 4, 5, 6] 
if position = 4, then [2, 3, 4, 5, 6, 7] 
if position = 5, then [3, 4, 5, 6, 7, 8] 
if position = 6, then [4, 5, 6, 7, 8, 9] 
if position = 7, then [5, 6, 7, 8, 9, 10] 
if position = 8, then [5, 6, 7, 8, 9, 10] 
if position = 9, then [5, 6, 7, 8, 9, 10] 
simply get the middle of N elements based on the position I pass. 

我可以写我自己的loop其中将包含多个if-else条件把它完成。但我觉得可能有一些简单的方法来做到这一点。

我没有包括我的不完整的代码片断,因为我强烈地感觉到必须有一些算法来做到这一点。

+1

如何使用的位置?当你指定位置为4时,为什么要跳过第一个元素? – fafl

+1

这就像,如果我的位置是阵列的中心位置,让我中间阵列有N个元素。这是否有意义 – Garfield

+0

好吧,我错过了,我得到一个开始索引和最小长度。我会相应地更新我的摘录。 :) –

回答

-2

不需要if-else你可以使用arr [position]到arr [8]。你有

function getArr(arr,position,requiredNumbers){ 
return arr.slice(position, position+requiredNumbers); 
} 
+0

不能理解谁和为什么downvoted? – anshuVersatile

1

简单的方法:

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

function getSubArray(idx, _length, _array) { 
    return _array.slice(idx, idx + _length); 
} 

var subArray = getSubArray(3, 6, a); 
+0

它工作的很好,但'getSubArray(5,6,a)=> [6,7,8,9,10]',我期望'[4,5,6,7,8,9]或[3, 4,5,6,7,8]'从位置5看起来中间。 – Garfield

+0

嘿@LonelyPlanet,我们的目标是通过一个初始的首发位置,不是吗?然后,计算转发项目。如果你想返回,'[4,5,6,7,8,9]',你应该调用'getSubArray(3,6,a)'。 –

0

你唯一需要的就是检查你不会去检查一个不存在的位置。像:

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
var n = 6; // Number of result you want 
var x = 8; // Pos you want 

// If you gonna exceed your length, we got only the n last element 
if((x+(n/2)) > a.length) { 
    console.log(a.slice(a.length-n)); 
// Otherwise, if under 0, we got the n first 
} else 
    if((x-(n/2)) < 0) { console.log(a.slice(0,n)); 
// Default case 
    } else { 
console.log(a.slice((x-(n/2)),(x+(n/2)))); 
} 

这不是最聪明的方式,但他可以给你一些提示。我用其他提到的片作为避免很多,但你应该做GENERIC测试。

0

事情是这样的:

a = [1,2,3,4,5,6,7,8,9,10]; 
n = 6; 
function split(position) { 
    var start = Math.min(Math.max(position - Math.floor(n/2), 0), a.length - n); 
    var stop = Math.min(start+n, a.length); 
    return a.slice(start, stop); 
} 
1

你可以使用的现在的位置偏移,并首先获得起始值为切片。

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
 
    n = 6, 
 
    i, 
 
    start; 
 

 
for (i = 1; i < 12; i++) { 
 
    start = Math.max(Math.min(i - n/2, a.length - n), 0); 
 
    console.log(i, ': ', a.slice(start, start + n).join());  
 
}

0

无需Math对象都没有。你可以简单地做如下:

function getArr(a,n,d){ 
 
    n = n - 4 < 0 ? 0 
 
       : a.length - d > n - 4 ? n - 3 
 
             : a.length - d; 
 
    return a.slice(n,n + d); 
 
} 
 

 
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
 
    diff = 6; 
 
for (var i = 0; i < 10; i ++) console.log(JSON.stringify(getArr(arr,i,diff)));