DEV Community

Mike
Mike

Posted on

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!

Latest comments (10)

Collapse
 
mellen profile image
Matt Ellen

I can sort that out, easy!

arr.sort((a, b) => a === 0 ? -1 : (b === 0) ? 1 : 0)
Collapse
 
ashishsurana profile image
Ashish Surana

How about this one :p

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]

Collapse
 
nestedl00p profile image
Nestor Rosales

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

Collapse
 
mitchmalinin profile image
Mitchell Malinin

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

Collapse
 
avalander profile image
Avalander • Edited

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 ]
Collapse
 
vskpro profile image
Sai Kiran Veeraneni • Edited

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

Collapse
 
louissimps profile image
Louie Simpson

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

Collapse
 
lehmannsystems profile image
Mike

love this solution - standard javascript and easy

Collapse
 
matgott profile image
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 ;)

Collapse
 
lehmannsystems profile image
Mike

glad it could be a good work break!