Javascript 按键值对对象数组进行排序

标签 javascript arrays sorting

我试图对包含状态键的对象数组进行排序,其中状态键具有“在线”,“离线”,“忙碌”,所以只想以所有“在线”都出现在顶部的方式对数组进行排序先“忙”,再“离线”

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];

arr.sort(function(first, second) {
   if (second.status == "online") return 1;

 });

console.log(arr);

这只会返回状态:顶部的“在线”。谢谢

最佳答案

试试这个:

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];
           
 var statusOrder = ["online", "busy", "offline"];
 
 arr = arr.sort(function(a, b) { 
     return statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status);
 });

 console.log(arr);

使用 ECMAScript6 甚至更短:

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];
           
 var statusOrder = ["online", "busy", "offline"];
 
 arr = arr.sort((a, b) => statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status));

 console.log(arr);

关于Javascript 按键值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46466513/

相关文章:

javascript - 如何在 CoffeeScript 中执行带减法的 for 循环?

javascript - classList.add 有效,但切换不起作用

javascript - 在单独的文件中指定路线时无法找到路线

javascript - grunt.task.run() 不工作

arrays - 按螺旋顺序打印矩阵

python - 为什么添加和分配 (+=) 与 numpy.ndarrays 行为异常?

java - Netbeans 建议将字段转换为最终字段,尽管我修改了该字段

mysql - 在 MySQL 中按数字顺序排序,然后按字母顺序排序

algorithm - 快速排序 "friendly"到 on-CPU 缓存吗?

javascript - lastclick var 未正确设置