如何基于对象索引值对JavaScript数组排序?附需求与代码
根据非唯一索引值排序数组
需求
需要根据对象cardIndices中的索引值对数组allCards进行排序,注意cardIndices的索引值并非唯一。
现有代码
const cardIndices = { 'card 1': 0, 'card 2': 1, 'card 3': 2, 'card 4': 3, 'card 5': 3, // 和card4索引值相同 }; const allCards = ['card 4', 'card 2', 'card 3', 'card 1', 'card 5'];
预期排序结果
['card 1', 'card 2', 'card 3', 'card 4', 'card 5']
错误尝试代码
const arr = [] for(let a = 0; a <= allCards; a++) { const card = allCards[a]; if(cardIndices[card] > cardIndices[allCards[a + 1]]) arr.push(card); }
正确解决方案
使用数组的sort方法自定义比较逻辑,分两步实现排序:
- 优先按
cardIndices中的索引值升序排列 - 索引值相同时,保持元素在原数组中的先后顺序(稳定排序)
// 复制原数组避免sort方法修改原数据 const sortedCards = [...allCards].sort((cardA, cardB) => { const idxA = cardIndices[cardA]; const idxB = cardIndices[cardB]; // 索引值不同时,按索引从小到大排列 if (idxA !== idxB) { return idxA - idxB; } // 索引值相同时,按原数组中的出现顺序排列 return allCards.indexOf(cardA) - allCards.indexOf(cardB); }); console.log(sortedCards); // 输出符合预期的结果
说明
[...allCards]用于复制原数组,因为sort是原地排序方法,直接调用会修改原数组- 当索引值相同时,通过
allCards.indexOf获取元素在原数组中的位置,保证card4在card5之前,和预期结果一致
内容的提问来源于stack exchange,提问作者Sara Ree
相关产品推荐
相关产品推荐

