admin管理员组

文章数量:1399912

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?

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?

Share Improve this question edited Mar 11, 2016 at 12:32 asked Mar 11, 2016 at 12:25 user2312612user2312612 1
  • [] and 0 are the same value but a different type. == matches value, === matches value and type. ([] == 0) > True, ([] === 0) > false, – Roboroads Commented Mar 11, 2016 at 12:31
Add a ment  | 

8 Answers 8

Reset to default 2

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

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

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>');

Another approach with swapping items.

function moveZeros(array) {
    var length = array.length,
        i = length;

    while (--i) {
        if (array[i] !== 0) continue;
        length--;
        while (i < length) {
            [array[i + 1], array[i]] = [array[i], array[i + 1]];
            i++;
        }
    }
    return array;
}

var array = [false, 1, 0, 1, 2, 0, 1, 3, "a"];

console.log(...moveZeros(array));

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

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

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
}

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

You could use the filter() method to achieve your goal. With the arrow notation you can shorten the code. For example: arr => arr === 0 is the shorthand for the anonymous filter function function(arr) { return arr === 0; }

var moveZeros = function (arr) {
    const zeros = arr.filter (arr => arr === 0);
    const others = arr.filter (arr => arr !== 0);
    return others.concat(zeros);
}
var arr = [false,1,0,1,2,0,1,3,"a"]
function moveZeros(arr){
var zeros = [];
var others = [];
var output;
for (var i=0; i< arr.length; i++){
if (arr[i]===0){
zeros.push(arr[i]);
}else{
others.push(arr[i])
}
}

output = others.concat(zeros);
console.log(output);
}

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

本文标签: javascriptWrite an algorithm that takes an array and moves all of the zeros to the endStack Overflow