使用ES6功能在数组中移动零



我是ES6的新手,试图创建一个函数,将数组中的所有零移动到数组的最后一个位置,同时保留数组的原始顺序例如[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;
} 

这是我的代码,它运行得很好,但我认为在使用一些ES6功能时,它可以更短。有人能提供更好的解决方案吗

使用filter函数和spread运算符可以很容易地解决这个问题。

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
};

根据评论中的要求:sort怎么样?

arr.sort((a, b) => -!b)

它肯定性能较差,但更短

Onecompileman得到了一个可以的解决方案,但由于OP想要"更短"的解决方案。我认为我们可以减少一些不必要的部分:

const moveZeros = a => [...a.filter(x => !!x), ...a.filter(x => !x)]

@lucifer63给出了一个简短而好的解决方案,但double not operator既无用又令人困惑,删除它会得到改进:

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]

您可以使用reduceRight,如果元素为0,则使用push,如果元素不为0,请使用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)

您可以通过在实际位置或调整后的索引处拼接结果数组来减少数组,该索引计算非空值。

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]));

最新更新