对数组项进行排序并保留相同元素的顺序

编程入门 行业动态 更新时间:2024-10-27 18:24:39
本文介绍了对数组项进行排序并保留相同元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有这个数组:

var array = [ { name: "border-color", value: "#CCCCCC" }, { name: "color", value: "#FFFFFF" }, { name: "background-color", value: "rgb(0, 0, 0)" }, { name: "background-color", value: "rgba(0, 0, 0, .5)" } ];

此函数按名称对数组进行排序:

And this function to sort the array by name:

array.sort(function(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; });

ECMAScript语言规范告诉我,:

排序不一定是稳定的(即比较的元素 相等并不一定要保持其原始顺序.

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

因此,排序后,名称=背景色的两个项目可以按任意顺序出现,即:

So, after sorting, the two items with name = background color could appear in any order i.e.:

[ { name: "background-color", value: "rgb(0, 0, 0)" }, { name: "background-color", value: "rgba(0, 0, 0, .5)" }, ... ]

[ { name: "background-color", value: "rgba(0, 0, 0, .5)" }, { name: "background-color", value: "rgb(0, 0, 0)" }, ... ]

如何对数组进行排序,以使具有相同名称的项目保持其相对顺序?我宁愿不对任何内容进行硬编码.

How can I sort the array so that items with same name maintain their relative order? I would rather not hardcode anything.

推荐答案

从理论上讲,在排序之前,您可以跟踪其在数组中的索引,并在排序时将其考虑在内.

Theoretically before sorting you could keep track of its index in the array and take that into account when sorting.

var sortArray = yourarray.map(function(data, idx){ return {idx:idx, data:data} }) sortArray.sort(function(a, b) { if (a.data.name < b.data.name) return -1; if (a.data.name > b.data.name) return 1; return a.idx - b.idx }); var answer = sortArray.map(function(val){ return val.data });

更多推荐

对数组项进行排序并保留相同元素的顺序

本文发布于:2023-11-30 00:57:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648192.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   顺序   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!