1

次のデータがあります。

var data = [[{x:"c", y:10}, {x:"a", y:20}, {x:"b", y:4}], [{x:"c", y:14}, {x:"a", y:22}, {x:"b", y:9}], [{x:"c", y:24}, {x:"a", y:65}, {x:"b", y:46}]]

最後の配列要素の 'y' 属性の値に基づいて、(親配列内の) 各配列の (x) 要素を並べ替える必要があります。結果は次のようになります。

[[{x:"c", y:10}, {x:"b", y:4}, {x:"a", y:20}], [{x:"c", y:14}, {x:"b", y:9}, {x:"a", y:22}], [{x:"c", y:24}, {x:"b", y:46}, {x:"a", y:65}]]

それを行う簡単な方法はありますか?データのグローバル構造は次のとおりです。

var data = [[{x:"x_1", y:}, {x:"x_2", y:},.. {x:"x_N", y:}], [{x:"x_1", y:}, {x:"x_2", y:},.. {x:"x_N", y:}], [{x:"x_1", y:}, {x:"x_2", y:},.. {x:"x_N", y:}]]

それぞれが N 個のハッシュ テーブルを含む 3 つの配列の配列があります。
最後の要素 (data[2]) の「y」キーの値に基づいて、すべてのハッシュ テーブルの要素を並べ替える必要があります。

4

3 に答える 3

0

期待される結果を得るには、このアルゴリズムを使用できます。これは 内のすべての配列に対する単なるループであり、一般的なsort-by-function でdataそれらをソートします:

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

> JSON.stringify(data)
[[{"x":"c","y":10},{"x":"b","y":4},{"x":"a","y":20}],[{"x":"c","y":14},{"x":"b","y":9},{"x":"a","y":22}],[{"x":"c","y":24},{"x":"b","y":46},{"x":"a","y":65}]]

あなたが記述しようとしたものではなく、xプロパティによって逆にソートされることに注意してください。


編集:今、私は仕事を得ました。アルゴリズムは次のとおりです。

// get the last element and sort it
var last = data[data.length-1];
last.sort(function(a,b){ return a.y-b.y; });

// get the sort order:
var order = last.map(function(o){ return o.x; }); // ["c", "b", "a"]

// now, reorder the previous arrays:
for (var i=0; i<data.length-1; i++) { // sic: loop condition is correct!
    // create a map for the items by their x property
    var hash = data[i].reduce(function(map, o){
        map[o.x] = o;
        return map;
    }, {});
    // create the new array by mapping the order
    data[i] = order.map(function(x) {
        return hash[x];
    });
};
于 2012-08-02T18:18:29.550 に答える
0
data.sort(function(a,b){return b.y-a.y});

http://www.w3schools.com/jsref/jsref_sort.asp

于 2012-08-02T15:16:25.707 に答える
0

デモの結果がどのように見えるかをアーカイブする方法はよくわかりませんが、テキストの内容が必要な場合は、これでうまくいきます。

ASC

data.sort(function(a, b) {
    return b[b.length-1].y - a[a.length-1].y;
});

説明

data.sort(function(a, b) {
    return a[a.length-1].y - b[b.length-1].y;
});
于 2012-08-02T15:17:52.713 に答える