JavaScript中一个对象数组按照另一个数组排序
需求:排序
const arr1 = [33, 11, 55, 22, 66];
const arr2 = [{age: 55}, {age: 22}, {age: 11}, {age: 66}, {age: 33}]
- 数组arr2中每项都是一个对象,对象中age属性 === 数组arr1中的项
- 将arr2数组根据对象的age值在arr1中的位置排序, 排序后的结果为 `const arr2 = [ {age: 33},{age: 11}, {age: 55}, {age: 22}, {age: 66}]
步骤:
方法1(需求已知根据对象的age排序)
const arr1 = [33, 11, 55, 22, 66]; const arr2 = [{age: 55}, {age: 22}, {age: 11}, {age: 66}, {age: 33}]console.log('排序前arr2 => ', arr2) // 排序 arr2arr2.sort((prev, next) => {const p = arr1.indexOf(prev.age)const n = arr1.indexOf(next.age)return p - n})// 排序 arr2(简写)arr2.sort((prev, next) => {return arr1.indexOf(prev.age) - arr1.indexOf(next.age)})console.log('排序后arr2 => ', arr2)console.log(' arr1 => ', arr1)
方法2 (需求未知需要根据对象的哪个属性排序)
const ageArr = [33, 11, 55, 22, 66]; const moneyArr = [5000, 3000, 6000, 2000, 9000]const objArr = [{age: 55, money: 6000},{age: 22, money: 3000},{age: 11, money: 2000},{age: 66, money: 9000},{age: 33, money: 5000}]// 1. 将sort排序函数抽离出来/*** @description 数组sort方法的 sortby(规定排序顺序)* @param {String} propName 属性名(数组排序基于的属性)* @param {Array} referArr 参照数组(objArr数组排序的参照数组)*/const sortFunc = (propName, referArr) => {return (prev, next) => {return referArr.indexOf(prev[propName]) - referArr.indexOf(next[propName])}}// 2. 排序objArrobjArr.sort(sortFunc('age', ageArr))console.log('按age属性排序后的objArr\n', objArr)objArr.sort(sortFunc('money', moneyArr))console.log('按money属性排序后的objArr\n', objArr)