2
1

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

JavaScriptで配列内オブジェクトの文字列ソート

Posted at

概要

JavaScriptの文字列ソートで少しハマったので記事にします。

やりたいこと

//before
var array2 = [
  {label:'apple'},
  {label:'かきくけこ'},
  {label:'computer'},
  {label:'あいうえお'},
  {label:'book'}
];
//after
/*
[
  {label:'apple'},
  {label:'book'},
  {label:'computer'},
  {label:'あいうえお'},
  {label:'かきくけこ'}
];
*/

単純な配列ならうまくいく

var array1 = ['apple','かきくけこ','computer','あいうえお','book'];
array1.sort();
//result
/*
['apple', 'book', 'computer', 'あいうえお', 'かきくけこ']
*/

連想配列のソートどうやるんだっけ??

この辺の記事を見つけてコピペしてみる
https://kinocolog.com/javascript_sort/

//before
var array2 = [
  {label:'apple'},
  {label:'かきくけこ'},
  {label:'computer'},
  {label:'あいうえお'},
  {label:'book'}
];
array2.sort(function(a, b){ return b.label - a.label});
//result
/*
[
  {label:'apple'},
  {label:'かきくけこ'},
  {label:'computer'},
  {label:'あいうえお'},
  {label:'book'}
];
*/

並び変わらない!?!?
なぜ??
結論:上記のかきかたは、数値比較にしか使えない。

比較演算子にすればうまくいく。

//before
var array2 = [
  {label:'apple'},
  {label:'かきくけこ'},
  {label:'computer'},
  {label:'あいうえお'},
  {label:'book'}
];
array2.sort(function(a,b){
  if(a.label > b.label){
    return 1;
  }else{
    return -1;
  }
});
//result
/*
[
  {label:'apple'},
  {label:'book'},
  {label:'computer'},
  {label:'あいうえお'},
  {label:'かきくけこ'}
];
*/

仕様を正しく理解してればわかるのですが、ハマったので、メモまで。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?