js数组根据另一个数组进行排序

在日常开发中碰到 自定义表头展示选择数据 需要按照前端定义的顺序(某种规则)展示数据,后端返回的顺序是不确定的,这个时候就需要进行排序来满足条件。记录一下。

// 后端返回数据
let arr1 = [{configItemKey: "robot.chargeFirst", configItemValue: "FALSE"},
{configItemKey: "robot.poseStatus", configItemValue: "FALSE"},
{configItemKey: "companyName", configItemValue: "FALSE"},
{configItemKey: "source", configItemValue: "TRUE"},
{configItemKey: "robot.ip", configItemValue: "FALSE"}]

// 前端数据
let arr2 = [{titleKey: 'time', key: 'breakdownTime'},
{titleKey: 'robot.iptime', key: 'robot.ip'},
{titleKey: 'robot.chargeFirsttime', key: 'robot.chargeFirst'},
{titleKey: 'time2', key: 'breakdownTime2'},
{titleKey: 'robot.poseStatustime', key: 'robot.poseStatus'},
{titleKey: 'companyNametime', key: 'companyName'},
{titleKey: 'sourcetime', key: 'source'}]

// 方法一
const Arr = arr2.map(item=> item.key)
arr1.sort((a,b) => Arr.indexOf(a.configItemKey) - Arr.indexOf(b.configItemKey))
console.log(arr1)


// 方法二
arr1.sort((a,b) => arr2.findIndex(item=>item.key == a.configItemKey) - arr2.findIndex(item=>item.key == b.configItemKey))
console.log(arr1)


// 简单数组
var arr1 = [52,23,36,11,09];
var arr2 = [23,09,11,36,52];
// 要求arr1按照arr2的顺序来排序,可以看到两个数组都不是常规的从小到大排序的

arr1.sort((a,b) => arr2.indexOf(a)-arr2.indexOf(b))

猜你喜欢

转载自blog.csdn.net/jiangzhihao0515/article/details/130250211