把两个数组按照其中一个数组的顺序 进行排序?

将oneArr 按照 twoArr 的顺序进行排序,而且两个数组可能一样长,也可能不一样长,
twoArr 是基于oneArr选中的数据,oneArr 是接口返回的数据,

oneArr = [

{

"intID": 4070479,

"sourceTableMetaId": 225378,

"strColumnNameEN": "id",

"strColumnDescZHCN": "ID",

"index": 0,

"_index": 0

},

{

"intID": 4070480,

"sourceTableMetaId": 225378,

"strColumnNameEN": "kpi_id",

"strColumnDescZHCN": "",

"index": 1,

"_index": 1

},

{

"intID": 4070481,

"sourceTableMetaId": 225378,

"strColumnNameEN": "kpi_code",

"strColumnDescZHCN": "xxx",

"index": 2,

"_index": 2

},

{

"intID": 4070482,

"sourceTableMetaId": 225378,

"strColumnNameEN": "project_code",

"strColumnDescZHCN": "xxxxx",

"index": 3,

"_index": 3

},

{

"intID": 4070481,

"sourceTableMetaId": 225373,

"strColumnNameEN": "key_code",

"strColumnDescZHCN": "xxxxxxxxxx",

"index": 4,

"_index": 4

}

]

twoArr = [

{

"intID": 4070479,

"sourceTableMetaId": 225378,

"strColumnNameEN": "id",

"strColumnDescZHCN": "ID",

"index": 0,

"_index": 0

},

{

"intID": 4070480,

"sourceTableMetaId": 225378,

"strColumnNameEN": "kpi_id",

"strColumnDescZHCN": "",

"index": 1,

"_index": 1

},

{

"intID": 4070482,

"sourceTableMetaId": 225378,

"strColumnNameEN": "project_code",

"strColumnDescZHCN": "xxxxx",

"index": 3,

"_index": 3

},

{

"intID": 4070481,

"sourceTableMetaId": 225378,

"strColumnNameEN": "kpi_code",

"strColumnDescZHCN": "xxxxxxx",

"index": 2,

"_index": 2

}

]


回答:

let sortIndex = twoArr.map(item => item.intID)

oneArr.sort((a, b) => sortIndex.indexOf(a.intID) - sortIndex.indexOf(b.intID))


回答:

let order = new Map(twoArr.map((item, index) => [item.intID, index]));

oneArr.sort((a, b) => {

let orderA = order.has(a.intID) ? order.get(a.intID) : Infinity;

let orderB = order.has(b.intID) ? order.get(b.intID) : Infinity;

return orderA - orderB;

});


回答:

  const newArr = [];

twoArr.forEach((twoE) => {

oneArr.forEach((oneE) => {

if (twoE.intID === oneE.intID) {

newArr.push(oneE);

}

});

});

console.log(newArr);


回答:

const cache = {};

oneArr.sort((a, b) => {

const aId = a.intID, bId = b.intID;

let aIndex = cache[aId] ?? -1;

let bIndex = cache[bId] ?? -1;

if (aIndex < 0 || bIndex < 0) {

for (let i = 0; i < twoArr.length; ++i) {

const id = twoArr[i].intID;

if (aId === id) aIndex = cache[aId] = i;

if (bId === id) bIndex = cache[bId] = i;

if (aIndex >= 0 && bIndex >= 0) break;

}

}

return aIndex - bIndex;

});

console.log(oneArr);

以上是 把两个数组按照其中一个数组的顺序 进行排序? 的全部内容, 来源链接: utcz.com/p/934416.html

回到顶部