下划线:在数组'排序之后,如何保持数组的顺序

Underscore: how to retain the order of this array after it's sorted?

本文关键字:数组 何保持 之后 顺序 下划线 排序      更新时间:2023-09-26

我有以下数组:

var myNumbers = [70.37037037037037, 11.11111111111111, 11.11111111111111, 7.4074074074074066];

我需要将每个数字四舍五入,并且它们的总和为100。如果不足,则按其小数部分的降序加1来弥补差额。这被称为Largest Remainder Method(我得到了以下代码形式如何使四舍五入的百分比加起来等于100%)。下面是得到这个的下划线代码:

var off = 100 - _.reduce(myNumbers, function(acc, x) {
    return acc + Math.round(x)
}, 0);
var rounded_percentages = _.chain(myNumbers)
    .sortBy(function(x) {
        return Math.round(x) - x
    })
    .map(function(x, i) {
        return Math.round(x) + (off > i) - (i >= (myNumbers.length + off))
    })
    .value();

结果是:

[8, 70, 11, 11]

这工作得很好,但顺序没有保留。我如何才能实现上述目标,同时保留顺序或使用对象而不是数组进行整个操作,并保留适当的键映射?

保留顺序后,结果应该是:

[70, 11, 11, 8]

使用键映射,初始变量看起来像:

var myNumbers = {
    firstNum: 70.37037037037037,
    secondNum: 11.11111111111111,
    thirdNum: 11.11111111111111,
    fourthNum: 7.4074074074074066
};

,结果将是:

{
    fourthNum: 8,
    firstNum: 70,
    secondNum: 11,
    thirdhNum: 11
};

不要改变数组的顺序。只创建一个排列(一个索引数组,然后根据每个索引指向的数组值的属性进行排序),并在其上运行您的算法。

var rounded_percentages = _.map(myNumbers, Math.floor);
var off = _.reduce(rounded_percentages, function(acc, x) { return acc - x; }, 100);
var permutation = _.sortBy(_.map(myNumbers, function(_, i) { return i; }), function(i) {
    return rounded_percentages[i] - myNumbers[i]; // those with the largest diff first
});
for (var i=0; i<off; i++)
    rounded_percentages[permutation[i]]++

这是一个更接近的实现最大剩余方法Math.round在你的实现是奇数。