基于 JavaScript 中的条件重新排序数组?
假设我们有一个对象数组,其中包含纸牌游戏中一些玩家的分数 −
const scorecard = [{ name: "Zahir", score: 23 }, { name: "Kabir", score: 13 }, { name: "Kunal", score: 29 }, { name: "Arnav", score: 42 }, { name: "Harman", score: 19 }, { name: "Rohit", score: 41 }, { name: "Rajan", score: 34 }];
我们还有一个变量 selfName,其中包含特定玩家的名字 −
const selfName = 'Arnav';
我们需要编写一个函数来按字母顺序对记分卡数组进行排序,并确保与 selfName 同名的对象出现在顶部(索引为 0)。
因此,让我们为这个问题编写代码 −
示例
const scorecard = [{ name: "Zahir", score: 23 }, { name: "Kabir", score: 13 }, { name: "Kunal", score: 29 }, { name: "Arnav", score: 42 }, { name: "Harman", score: 19 }, { name: "Rohit", score: 41 }, { name: "Rajan", score: 34 }]; const selfName = 'Arnav'; const sorter = (a, b) => { if(a.name === selfName){ return -1; }; if(b.name === selfName){ return 1; }; return a.name < b.name ? -1 : 1; }; scorecard.sort(sorter); console.log(scorecard);
输出
控制台中的输出为 −
[ { name: 'Arnav', score: 42 }, { name: 'Harman', score: 19 }, { name: 'Kabir', score: 13 }, { name: 'Kunal', score: 29 }, { name: 'Rajan', score: 34 }, { name: 'Rohit', score: 41 }, { name: 'Zahir', score: 23 } ]
广告