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?

JavaScriptでインデックスソート

Posted at

JavaScriptでインデックスソート

インデックスソート必要になるたびに思い出しながら実装してるのでメモ

インデックスソートとは?

var a = [2, 3, 1];
// ↓インデックスソートする
// > [2, 0, 1] と返ってくる
// a[2] = 1
// a[0] = 2
// a[1] = 3
// ソートした場合の参照インデックスを返してくれる

と返ってくるソートです

ソースコード

    function argsort(x) {
        var tmp = [];
        for(var i = 0; i < x.length; i += 1) {
            tmp.push([i, x[i]]);
        }
        tmp.sort(function(a, b) {
            return a[1] - b[1];
        });
        
        var idxs = [];
        for(var i = 0; i < tmp.length; i += 1) {
            idxs.push(tmp[i][0]);
        }
        return idxs;
    }
0
0
1

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?