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

JavaScript按多个(数字)字段排序数组

SEO心得admin37浏览0评论
本文介绍了JavaScript按多个(数字)字段排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何实现

ORDER BY sort1 DESC, sort2 DESC

JSON数组中的逻辑如下:

logic in an JSON array like such:

var items = '[ { "sort1": 1, "sort2": 3, "name" : "a", }, { "sort1": 1, "sort2": 2, "name" : "b", }, { "sort1": 2, "sort2": 1, "name" : "c", } ]';

产生新订单:

b,a,c

推荐答案

你应该相应地设计你的排序功能:

You should design your sorting function accordingly:

items.sort(function(a, b) { return a.sort1 - b.sort1 || a.sort2 - b.sort2; });

(因为 || 运算符的优先级较低比 - 一,这里没有必要使用括号。)

(because || operator has lower precedence than - one, it's not necessary to use parenthesis here).

逻辑很简单:if a.sort1 - b.sort1 表达式求值为0(所以这些属性相等),它将继续评估 || 表达式 - 并返回 a.sort2 - b.sort2 的结果。

The logic is simple: if a.sort1 - b.sort1 expression evaluates to 0 (so these properties are equal), it will proceed with evaluating || expression - and return the result of a.sort2 - b.sort2.

作为旁注,您的 items 实际上是一个字符串文字,你必须 JSON.parse 才能得到一个数组:

As a sidenote, your items is actually a string literal, you have to JSON.parse to get an array:

const itemsStr = `[{ "sort1": 1, "sort2": 3, "name": "a" }, { "sort1": 1, "sort2": 2, "name": "b" }, { "sort1": 2, "sort2": 1, "name": "c" } ]`; const items = JSON.parse(itemsStr); items.sort((a, b) => a.sort1 - b.sort1 || a.sort2 - b.sort2); console.log(items);

发布评论

评论列表(0)

  1. 暂无评论