javascript - 按键值对包含对象的 Javascript 数组进行排序

标签 javascript arrays sorting multidimensional-array nested

我正在尝试按数据键按字母顺序对下一个数组进行排序:

array = [
{index: 1,
 data: "d"
},
{index: 2,
 data: "c"
},
{index: 3,
 data: "a"
},
{index: 4,
 data: "f"
},
{index: 5,
 data: "e"
},
{index: 6,
 data: "b"
}
];

这样它就会变成如下:

array = [
{index: 3,
 data: "a"
},
{index: 6,
 data: "b"
},
{index: 2,
 data: "c"
},
{index: 1,
 data: "d"
},
{index: 5,
 data: "e"
},
{index: 4,
 data: "f"
}
];

已经找到并尝试了这样的事情:

array.sort(function (a, b) { return a[1] - b[1]; });

但没有成功。有没有一种简单的方法可以实现这一目标?请纯js。

最佳答案

您需要通过键而不是索引访问

let array = [{index: 1, data: "d"},{index: 2, data: "c"},{index: 3, data: "a"},{index: 4, data: "f"},{index: 5, data: "e"},{index: 6, data: "b"}];

array.sort( (f, s) => f.data.localeCompare(s.data) );

console.log(array);

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

相关文章:

javascript - 这种排序可以更优雅/递归吗

java - 测试我的堆

javascript - 单击按钮时 Ajax 重新加载 div 内容

javascript - 在较大的动画函数中添加围绕 3 个小动画的循环函数

javascript - 如何使用reduce按json分组?

c++ - 具有可变类型的构造函数的可变参数数量在 C++ 中创建变量私有(private)成员

java - 字符串中字符的快速排序

javascript - Promise 中的 XMLHttpRequest 进度事件

javascript - 不在 View 中时绝对固定在 View 中

java - 如何将点(.)分隔的字符串转换为数组列表?