17
16

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 5 years have passed since last update.

(Tips)オブジェクトのソート。複数の数値プロパティ

Posted at

僕がjavascriptを触りたての遥か昔にどこかで見たソート処理
ちょっと感心したのを覚えてる

(課題) line,columnで昇順にソートする

input.js
var errors = [
  {line: 1, column: 30, message: 'syntax error'},
  {line: 2, column: 21, message: 'too long'},
  {line: 2, column: 10, message: 'format invalid'},
  {line: 1, column:  5, message: 'delimiter error'}
];

// ここにソート処理をかけ

// 結果
// errors -> [
//  {line: 1, column:  5, message: 'delimiter error'},
//  {line: 1, column: 30, message: 'syntax error'},
//  {line: 2, column: 10, message: 'format invalid'},
//  {line: 2, column: 21, message: 'too long'}
// ];

愚直に書くとこんな感じなんだけど

sort.js
errors.sort(function(x, y){
  if (x.line < y.line) return -1;
  if (x.line > y.line) return 1;
  if (x.column < y.column) return -1;
  if (x.column > y.column) return 1;
  return 0;
});

比較対象が数字なら、次のように短くかけます

sort.js
errors.sort(function(x, y){
  return x.line - y.line || x.column - y.column;
});

今見ると、それほど不思議ではないんだけど、
ほんと最初に見た時は狐につままれた感じがしましたね
長らく使う事はなかったけど、たまたま機会があったので思い出しメモの投稿です

17
16
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
17
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?