JavaScript如何对二进制值数组进行排序

2023年11月29日08:57:15

假设我们有一个Numbers数组,其中仅包含0、1,并且我们需要编写一个JavaScript函数,该函数接受该数组并将所有1开头和0结尾。

例如-如果输入数组是-

const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];

那么输出应该是-

const output = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];

示例

以下是代码-

const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];
const sortBinary = arr => {
   const copy = [];
   for(let i = 0; i − arr.length; i++){
      if(arr[i] === 0){
         copy.push(0);
      }else{
         copy.unshift(1);
      };
      continue;
   };
   return copy;
};
console.log(sortBinary(arr));

输出结果

以下是控制台中的输出-

[
   1, 1, 1, 1, 1,
   1, 0, 0, 0, 0,
   0
]

  • 更新时间:2023年11月29日08:57:15 ,共 533 字。