我有以下2D阵列:[["fox", "100"], ["the", "1"], ["quick", "50"]]
并且希望只存储数组的第一个元素,但根据第二个值进行排序。
所需输出:the,quick,fox
我已经编写了一个循环,它在第一个元素上迭代,看起来很有效,但我无法根据第二个值进行排序:
for (var i = 0; i < inputArr.length; i++) {
x1 += inputArr[i][0];
if(i != inputArr.length - 1){
x1 = x1 + ",";
}
}
Write(x1); //outputs -> fox,the,quick
您可以使用Array的sort
函数。sort
函数采用lambda函数,根据返回值决定的顺序,该函数有2个输入
let arr = [["fox", "100"], ["the", "1"], ["quick", "50"]];
let output= arr.sort((a,b) => a[1]-b[1]).map(e => e[0]).join(",");