首页 文章资讯内容详情

在JavaScript中将右侧的所有0和左侧的1隔离

2026-06-04 1 花语

我们有一个数字数组,其中包含0、1和其他一些数字。我们需要编写一个JavaScript函数,该函数接受此数组并将所有1开头和0结尾。

让我们为该函数编写代码-

示例

const arr = [3, 2, 1, 8, 9, 0, 1, 9, 0, 2, 1, 0, 2, 0, 1, 0, 1, 1, 4, 0, 3]; const segregate = arr => { const copy = arr.slice(); for(let i = 0; i < copy.length; i++){ if(copy[i] === 0){ copy.push(copy.splice(i, 1)[0]); }else if(copy[i] === 1){ copy.unshift(copy.splice(i, 1)[0]); }; continue; }; return copy; }; console.log(segregate(arr));

输出结果

控制台中的输出将为-

[ 1, 1, 1, 3, 2, 8, 9, 1, 9, 2, 2, 1, 1, 4, 3, 0, 0, 0, 0, 0, 0 ]