将某些元素移至数组 JavaScript 的末尾
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 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 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

