js array sorted based on another array

In daily development, when you encounter custom header display selection data, you need to display the data in the order defined by the front end (certain rules). The order returned by the back end is uncertain. At this time, you need to sort to meet the conditions. Record it.

// 后端返回数据
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))

Guess you like

Origin blog.csdn.net/jiangzhihao0515/article/details/130250211