Write an algorithm that takes an array and moves all of the zeros to the end

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

For example:

moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]

My code:

var moveZeros = function (arr) {

var zeros = []; 
var others = [];
var res;

var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
if   (arr[i] ==  0) {
 zeros.push(arr[i]);
 } else {
      others.push(arr[i]);
 }
}
var res = others.concat( zeros );

return res;


}

I get the following result:

Expected:    ["a","b",null,"c","d",1,false,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0],
Instead got: ["a","b",null,"c","d",1,1,3,1,9,{},9,0,0,0,false,0,0,[],0,0,0,0,0]

The expected result is quite close to what I achieved (see above) . I don't understand why I have false in a different place?

Answers:

Answer

Please use === operator to compare if value is 0:

if (arr[i] ===  0) {
    zeros.push(arr[i]);
} else {
   others.push(arr[i]);
}
Answer

try this simply

var arr = [false,1,0,1,2,0,1,3,"a"];
arr.sort(function(a,b){if (a===0){return 1}});
document.body.innerHTML += JSON.stringify(arr);

Answer

Try to use a normal for loop and splice at this context to make your job done,

var arr = [false,1,0,1,2,0,1,3,"a"];
for(var i=arr.length;i>0;i--){
  if(arr[i] === 0){  arr.push(arr.splice(i,1).pop()); }
}
console.log(arr); //[false, 1, 1, 2, 1, 3, "a", 0, 0]
document.body.innerHTML += JSON.stringify(arr);

Answer

Use Array#splice() and Array#push().

function moveZeros(a) {
    var i = a.length - 1;
    while (i--) {
        if (a[i] === 0) {
            a.push(a.splice(i, 1)[0]);
        }
    }
    return a;
};

var array = [false, 1, 0, 1, 2, 0, 1, 3, "a"];
document.write('<pre>' + JSON.stringify(moveZeros(array), 0, 4) + '</pre>');

Answer

The code snippet below should work , please try , reason for null is that the length of the arr starts count from zero so when using <= you should subtract 1 from the total length.

var moveZeros = function (arr) {
  // TODO: Program me
  let zero = []
  let others = []
  let together = []
  
    for (let i =0; i <= arr.length-1; i++){
      if (arr[i] === 0){
        zero.push(arr[i])
        }
      else{ 
        others.push(arr[i])
      }
    }
  together = others.concat(zero)
  return together
}

Answer
var titleCase = function(title) {
var arr = [];
for (i = 0; i < title.length ; i++) {
    if (title[i] !== 0 ) {
        arr.push(title[i]);
    }
}
for (i = 0 ; i < title.length ; i++) {
    if (title[i] == 0 ) {
        arr.push(title[i]);
    }
}
return  arr;
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.