1

i have an array of mixed numbers, from that i need to shift the zero numbered to end without changing the nonzero numbers order in plain JAVASCRIPT.

Note: this need to be handled without creating a new array.

Ex:

inp_arr = [12,5,0,78,94,0,34,0,67];

expected output:

[12,5,78,94,34,67,0,0,0];

the way i implemented :

function sortArray(inputArray){
    let non_zeroArray = []
    let zero_Array = [];
    inputArray.map(item => {
        item != 0 ? non_zeroArray.push(item) : zero_Array.push(item)
    });
    return non_zeroArray.concat(zero_Array)
}

console.log(
  sortArray([32, 0, 12, 78, 0, 56, 0, 87, 0])
)
cнŝdk
  • 31,391
  • 7
  • 56
  • 78

7 Answers7

1

Your solution is quite well anyway as it has linear O(n) complexity. So you're not sorting the elements but filtering out the source array then pushing the zeroes at the end.

To improve readability you might use the native filter method.

If for some reason you need to move the other values you can use a second argument to the method.

In addition you might defer pushing the zeroes to the array during the iteration. Just to count them up and compose the array at the end.

const moveValueAtEnd = (arr, value) => {
  let counter = 0;
  return arr.filter((val) => {
    const match = val === value;
    enter code here
     // in js, boolean is casted to 0 or 1 when using arithmetic operation
     counter += match; 

     return !match;
  }).concat(Array(counter).fill(value))

}
abuduba
  • 4,986
  • 7
  • 26
  • 43
1

You can use array#sort to move 0 in the array to the last.

let arr = [12,5,0,78,94,0,34,0,67];
arr.sort((a,b) => (a === 0) - (b === 0));
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • As per ES2018 spec, the array.sort is guaranteed to be [stable](https://exploringjs.com/es2018-es2019/ch_array-prototype-sort-stable.html). – Hassan Imam Sep 25 '19 at 06:03
0

Pass a comparison function to array::sort. Only swap pairs if they aren't equal, and one is 0, else keep the existing order.

const data = [12,5,0,78,94,0,34,0,67];

const sortedData = data.sort((a, b) => {
  if (a !== b) {
    if (a === 0) return 1; // shift a back a place
    if (b === 0) return -1; // shift a forward a place
  }
  return 0; // keep in place
});

console.log(JSON.stringify(sortedData));
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
0

Well you can simply use Array#sort() method with a condition to check for 0 in the callback, it will directly update the current array:

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

Demo:

inp_arr = [12, 5, 0, 78, 94, 0, 34, 0, 67];

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

console.log(inp_arr);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

You need just two for loops. The outer loop goes though the array from the first element to the one before last and looks for zeros. If it finds one a second loop shifts the remaining elements one to the left, puts a zero at the end and reduces the remaining elements by one.

function collapse_zeros (a)
{
  let l = a.length;
  for (i = 0; i < l - 1; i++)
    if (a[i] == 0)
    {
      for (j = i; j < l - 1; j++)
        a[j] = a[j+1];
      a[l-1] = 0;
      l--;
    }
  return a;
}

console.log (collapse_zeros ([32, 0, 12, 78, 0, 56, 0, 87, 0]));
ceving
  • 21,900
  • 13
  • 104
  • 178
0
        function endZeroAppend(arr){
               arr.sort(function(a, b) {
           if(a==0 && b!=0)
               return 1;
           else if (a!=0 && b==0)
               return -1;
           else 
           return 0;
        });
               }
      console.log(endZeroAppend([1,0,2,0,0,9,0,6,7])) 

          //output: [1,2,9,6,7,0,0,0,0]
      
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Albert Logic Einstein Aug 20 '22 at 10:50
0
  let num = [1, 0, 0, 0, 5, 0, 5, 0, 0, 2, 3, 4, 0];
  let nonZero = num.filter((i) => {
    return i !== 0;
  });
  let zer = num.filter((i) => {
    return i === 0;
  });
  let newArr = [...nonZero, ...zer];