将特定元素移动到 JavaScript 数组的末尾
我们需要编写一个 JavaScript 函数,该函数以数组数字为第一个参数,以一个数字作为第二个参数。
我们的函数应检查数组中第二个数字的所有实例,如果存在任何实例,函数应将所有这些实例推送到数组的末尾。
如果输入数组是 -
const arr = [1, 5, 6, 6, 5, 3, 3];
而第二个参数是 6
那么数组应该变成 -
const output = [1, 5, 5, 3, 3, 6, 6];
示例
const arr = [1, 5, 6, 6, 5, 3, 3];
const num = 6;
const shiftElement = (arr, num) => {
if (arr.length === 0){
return arr
};
let index = 0; for(let e of arr){
if(e !== num){
arr[index] = e; index += 1;
};
}
for (; index < arr.length; index++){
arr[index] = num;
};
};
shiftElement(arr, num);
console.log(arr);输出
而控制台中的输出将是 -
[ 1, 5, 5, 3, 3, 6, 6 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP