[英]How can I sort a nested array representing different data sets in google apps script?
Please help me to understand how to sort a nested array which looks like the one presented in the code below.请帮助我了解如何对嵌套数组进行排序,该数组看起来像下面代码中所示的数组。
var arr2 = [
[["a",1,10,4],["a",3,6,7]],[["a",44,34,10]],
[["b",11,31,12],["b",110,88,77],["b",55,66,30]],
[["c",12,36,18],["c",18,66,71],["c",52,45,89]]
];
In my case each letter represents a specific product type dataset I'd like to analyse separately.在我的情况下,每个字母代表我想单独分析的特定产品类型数据集。 Hence it is important to me to sort each "product type array" on its own.
因此,对我来说,对每个“产品类型数组”进行单独排序很重要。 Also important to know, the number of "product type arrays" is not fixed to three.
同样重要的是要知道,“产品类型数组”的数量并不固定为三个。 It can be more or less.
它可以或多或少。 So the code should be flexible enough to handle a variable number of "product type arrays".
所以代码应该足够灵活以处理可变数量的“产品类型数组”。
In my example, let's say the first numeric value after product type identifier is the value I'd like to use for sorting.在我的示例中,假设产品类型标识符之后的第一个数值是我想用于排序的值。 How can I do that?
我怎样才能做到这一点?
I know how the sort function works in a less complex scenario but can't figure out how to apply this to the data above.我知道排序 function 如何在不太复杂的情况下工作,但无法弄清楚如何将其应用于上述数据。
var arr2 = [
["a",1,10,4],["a",3,6,7],["a",44,34,10]
];
var newArr2 = arr2.sort(function(r1,r2) {
var a = r1[1];
var b = r2[1];
return a-b;
});
Thanks for your help!谢谢你的帮助!
Edit 20/05/20: 20/05/20 编辑:
A more realistic data example that actually matches my data.一个更真实的数据示例,实际上与我的数据匹配。
var arr4 = [[["hansa bank - blau", "hansa bank - blau blau", 1, 10, 9], ["hansa bank - blau", "hansa bank - blau blau", 3, 6, 7], ["hansa bank - blau", "hansa bank - blau blau", 44, 34, 10]],
[["hansa bank - grün", "hansa bank - grün grün", 11, 31, 105], ["hansa bank - grün", "hansa bank - grün grün", 110, 88, 77], ["hansa bank - grün", "hansa bank - grün grün", 55, 66, 30]],
[["hansa bank - rot", "hansa bank - rot rot", 12, 36, 33], ["hansa bank - rot", "hansa bank - rot rot", 18, 66, 12], ["hansa bank - rot", "hansa bank - rot rot", 52, 45, 89]]];
You could iterate and apply the sorting for each array.您可以迭代并为每个数组应用排序。
var arr2 = [[["a", 1, 10, 4], ["a", 3, 6, 7]], [["a", 44, 34, 10]], [["b", 11, 31, 12], ["b", 110, 88, 77], ["b", 55, 66, 30]], [["c", 12, 36, 18], ["c", 18, 66, 71], ["c", 52, 45, 89]]]; arr2.forEach(a => a.sort(({ 1: a }, { 1: b }) => a - b)); console.log(arr2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.