如何将所有零元素移到数组的末尾?

时间:2019-05-27 17:29:28

标签: javascript arrays

编写一个函数,该函数接受一个值数组,并将所有零元素移到该数组的末尾,否则保留该数组的顺序。零元素还必须保持它们发生的顺序。

零元素由0或“ 0”定义。某些测试可能包含不是数字文字的元素。

不允许使用任何临时数组或对象。也不允许使用任何Array.prototype或Object.prototype方法。因此,不允许使用array.push或splice()。

我尝试过:

function removeZeros(nums) {

   for(let i = nums.length - 1; i >= 0 ; i--){
    if(nums[i] === 0){
      nums.splice(i, 1);
      nums.push(0);
    }
   }
   return nums;
}

输入:

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

预期:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

实际:

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

结果正确无误,但我需要在不使用array.push()或array.splice()

的情况下进行操作

5 个答案:

答案 0 :(得分:3)

  • 取原始数组的长度
  • 从原始数组中过滤非零值
  • 根据过滤后的数组和原始数组的长度差在结尾处添加零

function removeZeros(nums) {
   let originalLen = nums.length
   let nonZero = nums.filter(Boolean)
   return [...nonZero,...new Array(originalLen-nonZero.length).fill(0)]
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))


  

也不允许使用任何Array.prototype或Object.prototype   方法

function removeZeros(nums) {
   let originalLen = nums.length
   let final = []
   for(let i=0;i<nums.length; i++){
    if(nums[i]) final = [...final, nums[i]]
   }
   let lenDiff = originalLen-final.length
   while(lenDiff){
    final = [...final,0]
    lenDiff--
   }
   return final
}

console.log(removeZeros([7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]))

答案 1 :(得分:0)

使用for循环,遍历数组,并使用简单的条件检查零。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CategoryActivity">

   <android.support.design.widget.AppBarLayout
           android:theme="@style/AppTheme.AppBarOverlay"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

       <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:background="?attr/colorPrimary"
               app:popupTheme="@style/AppTheme.PopupOverlay"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize">
       </android.support.v7.widget.Toolbar>


   </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_category"
            android:layout_margin="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:layout_alignParentBottom="true"
            app:menu="@menu/bottom_nav_menu"/>

</LinearLayout>

答案 2 :(得分:0)

您可以使用sort

const arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

arr.sort((a, b) => (a === 0) - (b === 0))

console.log(arr)

减去布尔值将返回1,-1或0。

true - false === 1
false - true === -1
true - true === 0

如果a为0而b不是,则返回1,并将a移到数组的末尾。如果ab均为零或非零,则它们不会相对移动。

答案 3 :(得分:0)

function pushZeros(arr) {
  let count = 0; 
  for (let i = 0; i < arr.length; i++) {
      if (arr[i] !== 0) arr[count++] = arr[i]; 
  }
  while (count < arr.length) arr[count++] = 0;

  return arr;
}

基本上,我循环遍历数组的所有元素,在循环时选择非零元素,并将其从第0个位置存储在同一数组中。完成循环后,count将等于数组中的总非零元素。然后可以将其余的全部初始化为零。

答案 4 :(得分:0)

您可以简单地执行以下操作:

let data = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

let result = data.sort((a,b) => !!b-!!a)

console.log(result)

将对每个数组条目的布尔值进行排序的位置。我们通过double negation operator强制转换为布尔值。由于!!0为假,其他所有数字均为true,因此我们以降序排序(因此b-a而不是a-b),我们得到了期望的结果。

请注意,Array.sort会改变当前数组,如果要创建一个新数组,只需使用Array.slice,如下所示:

let data = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

let sortZeroesLast = arr => arr.slice().sort((a,b) => !!b-!!a)

console.log(data) // <-- original array
console.log(sortZeroesLast(data))  // <-- new sorted array

相关问题