## DEV Community 👩‍💻👨‍💻 is a community of 919,000 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Javascript Array Condensing

I have a cool challenge idea in Javascript.

Let's say you have an array of integers that can be any size. For example...

``````arr = [0, 0, 0, 4, 5, 1, 0, 5, 2, 0, 5];
``````

I challenge you to write a method that shifts all values greater than 0 to the front of the array. So the result would be...

``````arr = [4, 5, 1, 5, 2, 5, 0, 0, 0, 0, 0];
``````

GO!

## Top comments (10) Avalander • Edited on

Point-free ramda sorcery.

``````const {
compose,
equals,
flatten,
partition,
reverse,
} = require('ramda')

const f = compose(
flatten,
reverse,
partition(equals(0)),
)

f([ 0, 0, 0, 4, 5, 1, 0, 5, 2, 0, 5 ]) // [ 4, 5, 1, 5, 2, 5, 0, 0, 0, 0, 0 ]
`````` Louie Simpson

`arr.slice().filter(el => el !== 0).concat(arr.slice().filter(el => el == 0));` Mike

love this solution - standard javascript and easy matgott

function pushZeroesToEnd(a) {
const upZeroArray = a.filter(n => n > 0);
const zeroArray = a.filter(n => n == 0);
return upZeroArray.concat(zeroArray);
}

let arr = [4, 5, 1, 5, 2, 5, 0, 0, 0, 0, 0];
pushZeroesToEnd(arr);

IDK if the best implementation, but its faster and easy, specially for a work break ;) Mike

glad it could be a good work break! Sai Kiran Veeraneni • Edited on

function shifter(arr) {
const zero = [];
const numbers = [];
arr.forEach(item => {
if(item === 0){
zero.push(item);
} else {
numbers.push(item);
}
});
return ([...numbers,...zero]);
} Ashish Surana

``````const arr = [0, 0, 0, 4, 5, 1, 0, 5, 2, 0, 5];

Object.assign(Array(arr.length).fill(0), arr.filter(Boolean));

// [4, 5, 1, 5, 2, 5, 0, 0, 0, 0, 0]

`````` Matt Ellen

I can sort that out, easy!

``````arr.sort((a, b) => a === 0 ? -1 : (b === 0) ? 1 : 0)
`````` Mitchell Malinin

sortArray = (arr) => {
arr.reverse()
arr.forEach((singleElm,i)=>{
if(singleElm > 0){
arr.splice(i,1)
arr.unshift(singleElm)
}
})
return arr
} Nestor Rosales

const pushZerosToEnd = (arr) => arr.filter(n => n > 0).concat(arr.filter(n => n === 0));