按特定键值对对象数组进行排序Java脚本 [英] Sort Array of Objects by specific key value | Javascript

查看:175
本文介绍了按特定键值对对象数组进行排序Java脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从我正在从事的一个小型个人项目中对一组特定的对象进行排序.以前我从未遇到过使用Array.prototype.sort()函数的麻烦,但我想知道有关多个对象键的某些问题是否会影响它...

I'm having trouble sorting a specific array of objects from a small personal project I'm working on. I have never had trouble using the Array.prototype.sort() function before, but I wonder if something about the multiple object keys is affecting it...

盯着它看的时间比我想承认的要长,现在只需要寻求帮助即可. :|

Been staring at it for longer than I care to admit and just need to ask for help now. :|

目标:相对于每个对象上的特定key.value,按字母顺序对对象数组进行排序.

Goal: Sort array of objects alphabetically relative to a specific key.value on each of them.

提前谢谢!

JS小提琴在这里

JS Fiddle Here

排序函数示例-(尽管如此,我还是建议您查看完整的小提琴).

Sort function example - (I recommend looking at the full Fiddle for context though).

var sorted = array.sort((a, b) => { return a.key > b.key; });

已解决

@Ryan帮助我发现返回布尔值是不够的,您需要显式返回正数或负数或0.

@Ryan helped me find that returned a boolean isn't enough, you need to explicitly return a positive or negative number, or 0.

@Brk向我展示了一种很棒的快速方法.

@Brk showed me an awesome quick way to do it.

这篇文章有非常详细的描述. 在JavaScript中排序:不应该返回布尔值足以用作比较函数吗?

This post has a very detailed description. Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

谢谢!抱歉,帖子重复:|

Thanks all! Sorry for the duplicate post :|

推荐答案

您可以使用

You can use localeCompare method which will returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

var sorted = array.sort((a, b) => {
  return a.subreddit.localeCompare(b.subreddit)
});

演示

这篇关于按特定键值对对象数组进行排序Java脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆