根据位置从数组中获取N个元素

时间:2016-11-10 13:02:08

标签: javascript arrays algorithm

我想要一个返回子阵列的函数,该子阵列占据位置&没有。我想要的元素。我认为可能有一些算法可以找到支点或其他东西。从那我可以得到子阵列,但我完全忘了它。

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条件来完成它。但我觉得可能有一些简单的方法可以做到。

我没有包含我不完整的代码段,因为我强烈认为必须有一些算法来执行此操作。

7 个答案:

答案 0 :(得分:4)

你想要的是:Array.prototype.slice(...)

这里整齐地记录了: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);

答案 1 :(得分: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);

答案 2 :(得分:1)

您可以为postion使用偏移量,并首先获得切片的起始值。

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());      
}

答案 3 :(得分:0)

你唯一的需要是检查你是否不会检查一个不存在的pos。喜欢:

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))));
}

这不是最明智的方式,但他可以给你一些提示。我使用切片作为其他提及以避免大量的if,但你应该做 GENERIC 测试。

答案 4 :(得分: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);
}

答案 5 :(得分:0)

根本不需要Math对象。您可以按照以下步骤进行操作;

&#13;
&#13;
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)));
&#13;
&#13;
&#13;

答案 6 :(得分:-2)

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

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