DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

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

Create account Log in
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!

Top comments (10)

Collapse
 
avalander profile image
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 ]
Collapse
 
louissimps profile image
Louie Simpson

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

Collapse
 
lehmannsystems profile image
Mike Author

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 Author

glad it could be a good work break!

Collapse
 
vskpro profile image
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]);
}

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
 
mellen profile image
Matt Ellen

I can sort that out, easy!

arr.sort((a, b) => a === 0 ? -1 : (b === 0) ? 1 : 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
 
nestedl00p profile image
Nestor Rosales

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

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!