数组对象按某属性排序
时间: 2023-08-02 14:22:18 浏览: 107
可以使用 JavaScript 中的 `sort()` 方法来对数组中的对象按某个属性进行排序。
假设你有一个数组 `arr`,其中每个元素都是一个对象,对象有一个属性 `field`,表示需要按照该字段进行排序。你可以这样排序:
```javascript
arr.sort((a, b) => {
if (a.field < b.field) {
return -1;
} else if (a.field > b.field) {
return 1;
} else {
return 0;
}
});
```
这段代码中,我们使用 `sort()` 方法对数组进行排序,传入一个回调函数,该函数接收两个参数 `a` 和 `b`,分别表示数组中的两个元素。在回调函数中,我们比较这两个元素的 `field` 属性,如果 `a.field` 小于 `b.field`,则返回 -1,表示 `a` 应该排在 `b` 的前面;如果 `a.field` 大于 `b.field`,则返回 1,表示 `a` 应该排在 `b` 的后面;如果 `a.field` 等于 `b.field`,则返回 0,表示两个元素的顺序不变。
如果你需要按照某个属性进行降序排序,只需要将比较逻辑稍微修改一下即可:
```javascript
arr.sort((a, b) => {
if (a.field < b.field) {
return 1;
} else if (a.field > b.field) {
return -1;
} else {
return 0;
}
});
```
这样就可以按照某个属性对数组中的对象进行排序了。
阅读全文
相关推荐

















