2017-05-19 80 views
-1

我有一个这样的数组。 asd = [[a,3],[b,1],[c,5],[d,2]];如何在Apps脚本中对二维数组进行排序

我想将它从所得像的数量进行排序,

ASD = [[一,5],[B,3],[C,2],[d,1]];

任何人都知道应用程序脚本代码?

+0

这听起来像一个JavaScript题。无论如何,有几个问题:数组是否总是以[字母,数字]的形式出现?你想要按字母顺序排列字母,并且数字递减,即使这意味着要修改数组?您是否正在寻找专门用于Google应用程序脚本的解决方案,或者是否会影响电子表格中的单元格?请考虑回答这些问题,以便我们能够准确地帮助您。 – Adelin

+0

[为什么“有人可以帮助我?”不是一个真正的问题?](http://meta.stackoverflow.com/q/284236) –

回答

1

下面的样本如何? a,b,c和d被用作字符串。这可以在Google脚本编辑器上执行。

示例脚本:

var asd = [['a',3],['b',1],['c',5],['d',2]]; 

var result = [[asd[i][0],[i[1] for each (i in asd)].sort(
    function(a,b){ 
     if(a > b) return -1; 
     if(a < b) return 1; 
     return 0; 
})[i]] for (i in asd)]; 

结果:

[[a, 5.0], [b, 3.0], [c, 2.0], [d, 1.0]] 
0

假设你想达到什么样的,这个代码应工作:

var arr = [["a",3],["b",1],["c",5],["d",2]]; 

for (var i = 0; i < arr.length; i++){ 
for (var j = i+1; j < arr.length; j++) { 
    if (i==arr.length-1) continue; 
    var thisItem = arr[i], 
     nextItem = arr[j]; 
    if (thisItem[0] > nextItem[0]) { 
    var tempL = nextItem[0]; 
    nextItem[0] = thisItem[0]; 
    thisItem[0] = tempL; 
    } 

    if (thisItem[1] < nextItem[1]) { 
    var tempN = nextItem[1]; 
    nextItem[1] = thisItem[1]; 
    thisItem[1] = temp; 
    } 
} 
} 
相关问题