Arjun Kumar
Arjun Kumar

Reputation: 146

How to move all elements that are zero to the end of an array?

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 coming as correct but I need to do it without array.push() or array.splice()

Upvotes: 2

Views: 3518

Answers (6)

AKSHAY G
AKSHAY G

Reputation: 41

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]

Upvotes: 0

adiga
adiga

Reputation: 35222

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)

Upvotes: 3

Akrion
Akrion

Reputation: 18515

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

Upvotes: 0

noor
noor

Reputation: 1691

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.

Upvotes: 0

yaswanth
yaswanth

Reputation: 159

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

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

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

Upvotes: 3

Related Questions