javascript - How to move all elements that are zero to the end of an array? - Stack Overflow

Write a function that takes an array of values and moves all elements that are zero to the end of the a

Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

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;
}

input:

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

Expected:

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

Actual:

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

Result is ing as correct but I need to do it without array.push() or array.splice()

Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

NOT allowed to use any temporary arrays or objects. Also not allowed to use any Array.prototype or Object.prototype methods.So no array.push or splice() is allowed.

I tried this:

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;
}

input:

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

Expected:

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

Actual:

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

Result is ing as correct but I need to do it without array.push() or array.splice()

Share Improve this question edited May 27, 2019 at 18:48 Emma 27.8k11 gold badges48 silver badges71 bronze badges asked May 27, 2019 at 17:29 Arjun KumarArjun Kumar 1461 silver badge14 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3
  • Take length of original array
  • Filter nonZero values from original array
  • add zeros at the end as per difference in length of filtered array and original array

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]))


Also not allowed to use any Array.prototype or Object.prototype methods

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]))

You could use 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)

Subtracting booleans returns a 1, -1 or 0.

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

If a is 0 and b isn't, 1 will be returned and a will be moved to the end of the array. If both a and b are zero or non-zero, they aren't moved relative to each other.


The simplest way to move certain items to one end is to collect the items to 2 separate arrays based on the condition and concatenate them in the end.

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

for (const n of arr) {
  if (n === 0)
    zeros.push(n)
  else
    nonZeros.push(n)
}

const output = nonZeros.concat(zeros);
console.log(output)

Use a for loop, iterate through the array, and use a simple conditional to check zeroes.

var arr = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14];
var prev_zero_index = 0;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] != 0 && arr[i - 1] == 0) {
    prev_zero_index++;
    arr[prev_zero_index] = arr[i];
    arr[i] = 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;
}

Basically I am looping through all elements of array, picking nonzero element as I loop and storing it from 0th position in same array. After I am done looping, count will be equal to total nonzero elements in array. Rest all can be then initialized to zero.

You can simply do something like this:

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)

Where you would sort on the boolean value of each of the array entries. We cast to boolean via the double negation operator. Since !!0 would be false and every other number would be true and we sort in a descending order (hence b-a and not a-b) we get the desired result.

Please note that Array.sort mutates the current array and if you want to create a new one simply use Array.slice like this:

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

You could use the sort() to sort the list based on its equality to 0, like this!

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

numbers.sort((a, b) => {
  if (b === 0) return -1;
  return 1;
});

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744274162a4566246.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信