JavaScript 如何将指定数量的元素移动到数组的末尾
本文旨在使用JavaScript将一些指定的元素移动到数组的末尾。
给定一个长度为N的数组,将指定数量X的元素移动到给定数组的末尾。
输入:
arr = [1, 2, 3, 4, 5]
X = 2
输出: 以下数组应该作为输出,因为前两个数字被移动到数组的末尾。
[3, 4, 5, 1, 2]
方法1
- 首先,我们将从数组中提取前X个元素到一个新数组arr1中。
- 然后从数组中提取最后(N-X)个元素到一个新数组arr2中。
- 然后将arr1附加在arr2后面,得到结果数组。
示例:
// arr is the input array and x is the no.
// of elements that needs to be moved to
// end of the array
function moveElementsToEndOfArray(arr, x) {
let n = arr.length;
// if x is greater than length
// of the array
x = x % n;
let first_x_elements = arr.slice(0, x);
let remaining_elements = arr.slice(x, n);
// Destructuring to create the desired array
arr = [...remaining_elements, ...first_x_elements];
console.log(arr);
}
let arr = [1, 2, 3, 4, 5, 6];
let k = 5;
moveElementsToEndOfArray(arr, k);
输出
[ 6, 1, 2, 3, 4, 5 ]
方法2
- 使用for循环从索引i=0到X-1
- 在每次迭代中,将当前索引处的元素追加到数组末尾。
- 迭代完成后,使用JavaScript的splice()方法从数组中删除前X个元素以获得结果数组。
示例:
// Array is [1, 2, 3, 4, 5] and x = 2
// final output would be [3, 4, 5, 1, 2]
function moveElementsToEndOfArray(arr, x) {
x = x % (arr.length);
// After this loop array will
// be [1, 2, 3, 4, 5, 1, 2]
for (let i = 0; i < x; i++) {
arr.push(arr[i]);
}
// Splice method will remove first
// x = 2 elements from the array
// so array will be [3, 4, 5, 1, 2]
arr.splice(0, x);
console.log(arr);
}
let arr = [1, 2, 3, 4, 5];
let k = 2;
moveElementsToEndOfArray(arr, k);
输出
[ 3, 4, 5, 1, 2 ]
极客教程