最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Best practice when sorting an array in pure javascript, if I have to send one group to the back - Stack Overflow

programmeradmin1浏览0评论

If I have the following array:

[0, 1, 3, 0, 4, 2]

And I'd like to sort it ascending order, barring zeros which I need on the end:

[1, 2, 3, 4, 0, 0]

Bear in mind I don't have access to underscore or linq.js for this solution. My current solution works, but feels quite heavy, long, and not very elegant. Here's my code:

        function sortNumbers(numbers) {
        var zeroNumbers = [];
        var notZeroNumbers = [];

        for (var i = 0; i < numbers.length; i++) {
            if (numbers[i] === 0) {
                zeroNumbers.push(numbers[i]);
            } else {
                notZeroNumbers.push(numbers[i]);
            }
        }

        var sortedNumbers = notZeroNumbers.sort(function (a, b) {
            return parseFloat(a) - parseFloat(b);
        });

        for (var x = 0; x < zeroNumbers.length; x++) {
            sortedNumbers.push(zeroNumbers[x]);
        }

        return sortedNumbers;
    }

Can I improve on this solution?

If I have the following array:

[0, 1, 3, 0, 4, 2]

And I'd like to sort it ascending order, barring zeros which I need on the end:

[1, 2, 3, 4, 0, 0]

Bear in mind I don't have access to underscore or linq.js for this solution. My current solution works, but feels quite heavy, long, and not very elegant. Here's my code:

        function sortNumbers(numbers) {
        var zeroNumbers = [];
        var notZeroNumbers = [];

        for (var i = 0; i < numbers.length; i++) {
            if (numbers[i] === 0) {
                zeroNumbers.push(numbers[i]);
            } else {
                notZeroNumbers.push(numbers[i]);
            }
        }

        var sortedNumbers = notZeroNumbers.sort(function (a, b) {
            return parseFloat(a) - parseFloat(b);
        });

        for (var x = 0; x < zeroNumbers.length; x++) {
            sortedNumbers.push(zeroNumbers[x]);
        }

        return sortedNumbers;
    }

Can I improve on this solution?

Share Improve this question asked Jun 24, 2016 at 13:36 MGDaviesMGDavies 1,0542 gold badges17 silver badges30 bronze badges 2
  • 1 As a tip for future work with arrays, you should check out array functions, like .map, .sort, .filter, etc. – Frederik Witte Commented Jun 24, 2016 at 13:41
  • 1 Here's a great article for sorting and here's a big-o cheat sheet. – Anthony Commented Jun 24, 2016 at 13:44
Add a comment  | 

5 Answers 5

Reset to default 14

This is not related to this question, but I was searching for "pure sort javascript" and this is the first answer.

Because sort mutates the original array, the best practice when sorting an array is to clone it first.

const sortedArray = [...array].sort(/* optional comparison function*/)

simply try

var output = [0, 1, 3, 0, 4, 2].sort(function(a, b) {
  a = a || Number.MAX_SAFE_INTEGER; //if a == 0 then it will be a falsey value and a will be assigned Number.MAX_SAFE_INTEGER
  b = b || Number.MAX_SAFE_INTEGER;
  return a - b;
});

console.log(output)

var arr = [0, 1, 3, 0, 4, 2, 9, 8, 7, 0];
arr.sort(function (left, right) {
       return left == right ? 0 : (left === 0 ? 1 : (left < right ? -1 : 1));
});
console.log(arr)

This will always put zeroes at the end regardless of the size of the number.

Another alternative solution using Array.sort, Array.splice and Array.push functions:

var arr = [0, 1, 3, 0, 4, 2];
arr.sort();
while(arr[0] === 0) { arr.splice(0,1); arr.push(0); }

console.log(arr);  // [1, 2, 3, 4, 0, 0]

You can use sort for this, which takes a closure/callback.

var sortedArray = [0, 1, 3, 0, 4, 2].sort(function(currentValue, nextValue) {
    if(currentValue === 0) {
        return 1;
    } else {
        return currentValue - nextValue;
    }
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论