[英]Rotate an array at a specific index in JavaScript
I have aa position and an array of users我有一个职位和一组用户
const position = 2
const users = ["John", "Mary", "Daniel", "Michael"]
I want to generate a new array (or reorder it) starting from the position.我想从位置开始生成一个新数组(或重新排序)。
In the case of position = 2 the generated array should be在 position = 2的情况下,生成的数组应该是
users = ["Daniel", "Michael", "John", "Mary"]
In the case of position = 3 the generated array should be在 position = 3的情况下,生成的数组应该是
users = ["Michael", "John", "Mary", "Daniel"]
In the case of position 0 (no changes) the generated array should left intact在位置0 (无变化)的情况下,生成的数组应保持不变
const users = ["John", "Mary", "Daniel", "Michael"]
how can I achieve this?我怎样才能做到这一点?
You could use map()
or Array.from()
to make a new array from the index + your offset using the modulus operator to wrap around:您可以使用map()
或Array.from()
从索引 + 您的偏移量使用模数运算符创建一个新数组来环绕:
const position = 2 const users = ["John", "Mary", "Daniel", "Michael"] const rotate = (arr, position) => Array.from(arr, (_, index) => arr[(index + position) % arr.length]) console.log(rotate(users, 0)) console.log(rotate(users, 1)) console.log(rotate(users, 2)) console.log(rotate(users, 3))
You can use Array#slice
from 0..pos
and from pos..length
to divide the array into two chunks at the split index.您可以使用Array#slice
from 0..pos
和 from pos..length
在拆分索引处将数组分成两个块。 Then swap the chunks and either spread or concat
the two subarrays back together.然后交换块并将两个子concat
展开或连接在一起。 Take the mod of the position to keep the rotation in-bounds.取位置的 mod 以保持旋转在界内。
const rotate = (arr, i) => { i %= arr.length; return [...arr.slice(i), ...arr.slice(0, i)]; }; for (let i = -1; i < 5; i++) { console.log(rotate(["John", "Mary", "Daniel", "Michael"], i)); }
Simple way to do that.这样做的简单方法。
function reorder(arr, pos){
var output = [];
for(var i = pos;i<arr.length;i++){
output.push(arr[i]);
}
for(var i = 0;i<pos;i++){
output.push(arr[i]);
}
return output;
}
Not sure how efficient is this.不确定这有多有效。 There must be better ways to do this.必须有更好的方法来做到这一点。
You can use a shift() + push() combinaison您可以使用shift() + push()组合
users.push(users.shift());
...and then loop it by the position number. ...然后按位置编号循环。
const users = ["John", "Mary", "Daniel", "Michael"]; let position; function rotate(array, index){ for(let i = 0; i < index; i++){ array.push(array.shift()); } console.log(`Position: ${index}`); console.log(array); } // Test Zone position = 0; rotate(users, position); position = 1; rotate(users, position); position = 2; rotate(users, position); position = 3; rotate(users, position);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.