拆分数组保持中心选择的索引

时间:2017-10-27 22:07:20

标签: javascript arrays

我有一个像这样的数组:[ 'a', 'b', 'c', 'd', 'e' ]。我需要将它分成一半,但选择一个索引作为新的中心,即在索引选择为新中心之前和之后始终保持相同数量的元素。所需结果的例子:

// index: 1
[ 'e', 'a', 'b', 'c', 'd' ]

// index: 3
[ 'b', 'c', 'd', 'e', 'a' ]

我尝试了slice和负值的一些事情:

(function splitChosingMiddle(arr, index) {
  const half = Math.floor(arr.length / 2)
  return [
    ...arr.slice(index - half),
    ...arr.slice(index, half + 1)
  ]
})([ 'a', 'b', 'c', 'd', 'e' ], 0)

但它只有在新中心是0索引时才有效,任何其他索引都会使逻辑崩溃。我相信我误解了splice使用负长度。

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

找到索引和中间值之间的差值,使用delta对项目进行切片以将该数量移动到数组的开头/结尾:



function splitChosingMiddle(arr, index) {
  const half = Math.floor((arr.length) / 2)
  const delta = index - half

  return [
    ...arr.slice(delta, arr.length),
    ...arr.slice(0, delta)
  ]
}

console.log(JSON.stringify(splitChosingMiddle([ 'a', 'b', 'c', 'd', 'e' ], 0)));
console.log(JSON.stringify(splitChosingMiddle([ 'a', 'b', 'c', 'd', 'e' ], 1)));
console.log(JSON.stringify(splitChosingMiddle([ 'a', 'b', 'c', 'd', 'e' ], 2)));
console.log(JSON.stringify(splitChosingMiddle([ 'a', 'b', 'c', 'd', 'e' ], 3)));
console.log(JSON.stringify(splitChosingMiddle([ 'a', 'b', 'c', 'd', 'e' ], 4)));




答案 1 :(得分:0)

尝试一下这个

function rotate (array, index) {
  var head = array.slice();
  var tail = head.splice(array.length - index, index);
  return tail.concat(head);
}

应该做的伎俩。但试着去了解它

答案 2 :(得分:-1)

这看起来像CS的家庭作业问题,所以我会给出一个暗示而不是直接的解决方案来为你节省一些乐趣。

看起来index是一些轮换 - 即从列表中取出最后一项并放在开头(javascript包含shiftpop可能会有所帮助)。