js中对象数组按照另一个对象数组的某一项排序
有对象数组 arr1 和 arr2, 现在 arr2 需要按照 arr1 中的 checkItems 的值来排序
const arr1 = [
{checkItems: 'A'},
{checkItems: 'B'},
{checkItems: 'C'},
]
const arr2 = [
{checkItems: 'B', name: 'BBB'},
{checkItems: 'C', name: 'CCC'},
{checkItems: 'A', name: 'AAA'},
]
使用排序方法如下
const sortList = (list, needSort) => {
const _list = list.map(li => li.checkItems) // ['A', 'B', 'C']
return needSort.sort((a, b) => {
return _list.indexOf(a.checkItems) < _list.indexOf(b.checkItems) ? -1 : 1;
});
}
const _arr2 = sortList(arr1, arr2)
// 打印结果为
// [
// {checkItems: 'A', name: 'AAA'},
// {checkItems: 'B', name: 'BBB'},
// {checkItems: 'C', name: 'CCC'},
// ]