2016-11-10 73 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)));