0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript】配列内の値に順位をつける

Posted at

順位付け?

配列の値を並び替えすることはありましたが、順位付けする方法は??となり、メモします。

const array = [ 90, 100, 50, 10, 80 ]

// 並び替え(降順)
const sorted = array.slice().sort((a,b) => b - a); 

// 元配列と並び替えた配列を比較
const ranked = array.slice().map((item) => {
  return sorted.indexOf(item) + 1
})

console.log(ranked);

// 出力    
// [ 2, 1, 4, 5, 3 ]

余談

sortは破壊的変更になるので、それを防ぐ方法

const array = [ 90, 100, 50, 10, 80 ]

// 破壊的変更
array2 = array.sort((a,b) => b - a);

console.log(array);  // [ 100, 90, 80, 50, 10 ]
console.log(array2); // [ 100, 90, 80, 50, 10 ]


// 防ぐ
array3 = array.slice().sort((a,b) => b - a); 

console.log(array);  // [ 90, 100, 50, 10, 80 ]
console.log(array3); // [ 100, 90, 80, 50, 10 ]

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?