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 }
] -
JavaScriptでオブジェクトプロパティ名の配列を置き換える
以下は、JavaScriptでオブジェクトプロパティ名の配列を置き換えるコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style&g
-
JavaScriptでツリー化するオブジェクトのフラット配列
このようなオブジェクトの配列があるとします- const arr = [ { id: '1', name: 'name 1', parentId: null }, { id: '2', name: 'name 2', parentId: null }, { id: '2_1', name: 'name 2_1', parentId: '2' }, { id: '2_2