我正在尝试按数据键按字母顺序对下一个数组进行排序:
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/