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)
Point-free ramda sorcery.
arr.slice().filter(el => el !== 0).concat(arr.slice().filter(el => el == 0));
love this solution - standard javascript and easy
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 ;)
glad it could be a good work break!
function shifter(arr) {
const zero = [];
const numbers = [];
arr.forEach(item => {
if(item === 0){
zero.push(item);
} else {
numbers.push(item);
}
});
return ([...numbers,...zero]);
}
How about this one :p
I can sort that out, easy!
sortArray = (arr) => {
arr.reverse()
arr.forEach((singleElm,i)=>{
if(singleElm > 0){
arr.splice(i,1)
arr.unshift(singleElm)
}
})
return arr
}
const pushZerosToEnd = (arr) => arr.filter(n => n > 0).concat(arr.filter(n => n === 0));