admin 管理员组文章数量: 1086019
I’m new to ES6, trying to make a function that moves all zeros in the array in the last position of the array while preserving the original order of the array
E.g. [1,0,0,0,2,3,4,5]
=> [1,2,3,4,5,0,0,0]
function moveZeros (arr) {
let zeroArr = [];
for(let i = 0;i < arr.length;i++) {
if (arr[i] == 0) {
zeroArr.push(arr[i]);
arr.splice(i, 1);
}
}
arr.push(...zeroArr);
return arr;
}
This is my code its works fine, but I think this can be shorter more in using some ES6 features. Can someone provide a better solution
I’m new to ES6, trying to make a function that moves all zeros in the array in the last position of the array while preserving the original order of the array
E.g. [1,0,0,0,2,3,4,5]
=> [1,2,3,4,5,0,0,0]
function moveZeros (arr) {
let zeroArr = [];
for(let i = 0;i < arr.length;i++) {
if (arr[i] == 0) {
zeroArr.push(arr[i]);
arr.splice(i, 1);
}
}
arr.push(...zeroArr);
return arr;
}
This is my code its works fine, but I think this can be shorter more in using some ES6 features. Can someone provide a better solution
Share Improve this question edited Dec 5, 2018 at 11:29 shen asked Dec 5, 2018 at 11:26 shenshen 434 bronze badges 1- euuuh. What about a regular sort?... – briosheje Commented Dec 5, 2018 at 11:27
5 Answers
Reset to default 7That can be solved easily using filter
function and spread
operator, .
const moveZeros = arr => {
const z = arr.filter(a => a === 0); // get all zeroes
const nZ = arr.filter(a => a !== 0); // get all non zeroes
return [...nZ, ...z]; // put the zeroes on the last position
};
As requested in ments: what about sort
?
arr.sort((a, b) => -!b)
It is for sure less performant, but hella shorter
Old
Onepileman got an ok solution, but as OP wanted 'shorter' solution, i think we can reduce some unnecessary parts:
const moveZeros = a => [...a.filter(x => !!x), ...a.filter(x => !x)]
@lucifer63 gave a short and good solution but the double not operator
is both useless and confusing, removing it you'll get an improvement:
const moveZeros = z => [...z.filter(a => a), ...z.filter(a => !a)]
moveZeros([1,0,0,0,2,3,4,5])
// [1, 2, 3, 4, 5, 0, 0, 0]
You could use reduceRight
and if the element is 0 use push
or if its not 0 use unshift
.
const arr = [1,0,0,0,2,3,4,5];
const res = arr.reduceRight((r, e) => (e === 0 ? r.push(e) : r.unshift(e), r), [])
console.log(res)
You could reduce the array by splicing the result array either on the actual position or at an adjusted index, which counts the not null values.
function moveZeroes(array) {
return array.reduce((i => (r, v, j) => (r.splice(!v ? j : i++, 0, v), r))(0), []);
}
console.log(moveZeroes([1, 0, 0, 0, 2, 3, 4, 5]));
本文标签: javascriptMove zeroes in array using ES6 featuresStack Overflow
版权声明:本文标题:javascript - Move zeroes in array using ES6 features - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744076707a2529483.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论