在数组上使用Javascript .sort()将所有零放在最后 [英] Using Javascript .sort() on an array to put all the zeros at the end

查看:204
本文介绍了在数组上使用Javascript .sort()将所有零放在最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对数组进行排序,以使所有零都在末尾.但是,我不希望列表按数字排序,所有大于零的数字应保持相同的顺序.这是到目前为止我得到的:

I am trying to sort an array so that all the zeros are at the end. However, I don't want the list to be numerically sorted, all the numbers above zero should stay in the same order. Here's what I've got so far:

function placeZerosAtEnd(arr) {
    return arr.sort(compareForSort);
}
function compareForSort(first, second) {
    return first == 0 ? 1 : 0;
}
placeZerosAtEnd([9,0,9,1,0,2,0,1,1,0,3,0,1,9,9,0,0,0,0,0]);

这应该返回[9,9,1,2,1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0],但实际上返回[3,9,9,1,9,2,9,1,1,1,0,0,0,0,0,0,0,0,0,0].零是正确的,但其他数字的排列顺序却很奇怪.这是怎么回事?

This should return [9,9,1,2,1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0], but actually returns [3,9,9,1,9,2,9,1,1,1,0,0,0,0,0,0,0,0,0,0]. The zeros are correct, but the other numbers are in a strange order. What is going on here?

http://jsfiddle.net/v67fx4zk/

推荐答案

正如其他人所说,在这种情况下使用.sort()是错误的.这是我最后使用的代码,正如Elclanrs在我的第一篇文章下面的评论中所建议的那样.

As other have said, using .sort() was wrong in this instance. This is the code I used in the end, as suggested by elclanrs in the comments below my initial post.

function placeZerosAtEnd(arr) {
    return arr.filter(isntZero).concat(arr.filter(isZero));
}
function isntZero(element) {
    return element > 0;
}
function isZero(element) {
    return element == 0;
}

这篇关于在数组上使用Javascript .sort()将所有零放在最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆