简体   繁体   English

对数组进行排序

[英]Sort array of arrays

I have the following data: 我有以下数据:

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}]]

I need to order the (x) element of each array (within the parent array) based on the value of the 'y' attributes from the last array element. 我需要基于最后一个数组元素的y属性值对每个数组(父数组内)的(x)元素进行排序。 The result would be: 结果将是:

[[{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}]]

Any easy way to do that? 有什么简单的方法吗? Here's the global structure of the data: 这是数据的全局结构:

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:}]]

I have an array of 3 arrays that each contains N hash tables. 我有3个数组的数组,每个数组包含N个哈希表。
I need to order the elements in all hash tables based on the values of the 'y' key from the last element (data[2]). 我需要根据最后一个元素(data [2])中“ y”键的值对所有哈希表中的元素进行排序。

data.sort(function(a,b){return b.y-a.y});

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

I can't really see how you can archive what your demo result looks like but if you want what your text says this will do the job. 我真的看不到如何保存演示结果的样子,但是如果您想要文本说明的话,就可以完成工作。

ASC ASC

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

DESC 数据中心

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

To get the expected result, you can use this algorithm. 要获得预期的结果,可以使用此算法。 It is just a loop over all arrays in data , and sorts them with the common sort-by-function : 它只是对data所有数组的循环,并使用常见的sort-by-function对它们进行排序

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}]]

Note that it does not what you tried to describe, but sorts reverse by the x property. 请注意,它不是您要描述的内容,而是按x属性进行反向排序。


EDIT: Now I got the task. 编辑:现在我得到了任务。 Here's the algorithm: 这是算法:

// 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];
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM