gpt4 book ai didi

JavaScript 数组对象排序未按预期工作

转载 作者:行者123 更新时间:2023-11-30 07:34:08 24 4
gpt4 key购买 nike

我的数组对象如下

 var data = [{"weight":0,"name":"New Arrivals"},{"weight":0,"name":"Weekly Promotions"},{"weight":0,"name":"Sale"},{"weight":0,"name":"Extended Size"},{"weight":0,"name":"Accessories and Shoes"},{"weight":0,"name":"Activewear"},{"weight":0,"name":"Disney Project"},{"weight":0,"name":"Dresses and Jumpsuits"},{"weight":0,"name":"Fleece"},{"weight":0,"name":"HEATTECH Collection"},{"weight":0,"name":"Ines de la Fressange"},{"weight":0,"name":"Intimates"},{"weight":0,"name":"Jeans"},{"weight":0,"name":"Loungewear"},{"weight":0,"name":"Outerwear and Blazers"},{"weight":0,"name":"Pants"},{"weight":0,"name":"Shirts and Blouses"},{"weight":0,"name":"Skirts"},{"weight":0,"name":"Socks and Hosiery"},{"weight":0,"name":"Sweaters"},{"weight":0,"name":"Sweatshirts and Sweatpants"},{"weight":0,"name":"T-Shirts and Tops"},{"weight":0,"name":"UT: Graphic Tees"},{"weight":0,"name":"Wear To Work"},{"weight":0,"name":"Mix and Match"}]

我正在尝试根据属性权重对其进行排序,但如果所有权重值均为 0,我需要原始顺序,因为它在输出中。但是此功能没有按预期工作,而是顺序发生了变化。

用过ramda和JavaScript排序

var sortedData = R.sortBy(R.prop('weight'), data);

var sortData = data.slice(0);
sortData.sort(function(a,b) {
return a.weight - b.weight;
});

两种情况都得到如下结果

var output = [{"weight":0,"name":"Jeans"},{"weight":0,"name":"New Arrivals"},{"weight":0,"name":"Sale"},{"weight":0,"name":"Extended Size"},{"weight":0,"name":"Accessories and Shoes"},{"weight":0,"name":"Activewear"},{"weight":0,"name":"Disney Project"},{"weight":0,"name":"Dresses and Jumpsuits"},{"weight":0,"name":"Fleece"},{"weight":0,"name":"HEATTECH Collection"},{"weight":0,"name":"Ines de la Fressange"},{"weight":0,"name":"Intimates"},{"weight":0,"name":"Weekly Promotions"},{"weight":0,"name":"Loungewear"},{"weight":0,"name":"Outerwear and Blazers"},{"weight":0,"name":"Pants"},{"weight":0,"name":"Shirts and Blouses"},{"weight":0,"name":"Skirts"},{"weight":0,"name":"Socks and Hosiery"},{"weight":0,"name":"Sweaters"},{"weight":0,"name":"Sweatshirts and Sweatpants"},{"weight":0,"name":"T-Shirts and Tops"},{"weight":0,"name":"UT: Graphic Tees"},{"weight":0,"name":"Wear To Work"},{"weight":0,"name":"Mix and Match"}]

预期:当所有情况的权重值为 0 时,我预期结果与输入相同。

感谢任何帮助。

最佳答案

您的问题是不能保证 JavaScript 中的排序是稳定的。ECMA-262 规范说明了这一点:

The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order).

问题Fast stable sorting algorithm implementation in javascript包括指向 this Vjeux blog post 的链接这说明了稳定排序以及其他几个选项。

关于JavaScript 数组对象排序未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39673953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com