按键值对包含对象的Javascript数组排序

按键值对包含对象的Javascript数组排序,javascript,arrays,sorting,multidimensional-array,nested,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:

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

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。

您可以使用

var数组=[{index:1,数据:“d”},{index:2,数据:“c”},{index:3,数据:“a”},{index:4,数据:“f”},{index:5,数据:“e”},{index:6,数据:“b”}];
sort(函数(a,b){返回a.data.localeCompare(b.data);});
console.log(数组)

.as控制台包装{max height:100%!important;top:0;}
您需要通过键而不是索引进行访问

let数组=[{index:1,数据:“d”},{index:2,数据:“c”},{index:3,数据:“a”},{index:4,数据:“f”},{index:5,数据:“e”},{index:6,数据:“b”}];
sort((f,s)=>f.data.localeCompare(s.data));
console.log(数组)