假设我们有一个对象数组,其中包含纸牌游戏中某些玩家的得分-
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 } ]