按特定顺序对多维数组排序

时间:2018-08-25 12:29:14

标签: javascript arrays sorting

我已经思考了很长时间了,如何以自己想要的方式在Javascript中对数组进行排序,尝试了各种方法,但我无法提出解决方案,所以我决定在这里询问... 简而言之,我的数组看起来像这样复杂:

var englishvoc = new Array();

englishvoc[0] = new Array();
englishvoc[0][0] = "beautiful";
englishvoc[0][1] = new Array();
englishvoc[0][1][0] = 0;
englishvoc[0][2] = 2;

englishvoc[1] = new Array();
englishvoc[1][0] = "nice";
englishvoc[1][1] = new Array();
englishvoc[1][1][0] = 0;
englishvoc[1][2] = 2;

englishvoc[2] = new Array();
englishvoc[2][0] = "get";
englishvoc[2][1] = new Array();
englishvoc[2][1][0] = 9;
englishvoc[2][1][1] = 7;
englishvoc[2][1][2] = 2;
englishvoc[2][2] = 1;

我希望对数组进行排序的方式只是通过其中的英语单词进行排序,以便在移动数组的整个第一个维度的同时,它们的顺序变得“美丽”,“获取”,“很好”。结果应该是:

alert(englishvoc) //Returns: '"beautiful",0,2,"get",9,7,2,1,"nice",0,2'

此外,如果此排序系统不区分大小写,那就太好了... 也许有人为复杂的数组排序提供了解决方案? 预先感谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试sort()和localeCompare()

var englishvoc = new Array();

englishvoc[0] = new Array();
englishvoc[0][0] = "beautiful";
englishvoc[0][1] = new Array();
englishvoc[0][1][0] = 0;
englishvoc[0][2] = 2;

englishvoc[2] = new Array();
englishvoc[2][0] = "nice";
englishvoc[2][1] = new Array();
englishvoc[2][1][0] = 0;
englishvoc[2][2] = 2;

englishvoc[7] = new Array();
englishvoc[7][0] = "get";
englishvoc[7][1] = new Array();
englishvoc[7][1][0] = 9;
englishvoc[7][1][1] = 7;
englishvoc[7][1][2] = 2;
englishvoc[7][2] = 1;



englishvoc.sort((a,b)=>a[0].localeCompare(b[0]))

console.log(englishvoc.join())

答案 1 :(得分:-1)

To me it looks like you are trying to represent an object array as multi dimensional array.  I think you should be able to represent like below.  


[{
    name:  "beautiful";
    data: {
            val1: [0]
            val2: [1]
        }
    },
    {
    name:  "nice";
    data: {
            val1: [0]
            val2: [1]
        }
    },
    {
    name:  "get";
    data: {
            val1: [9]
            val2: [7,2]
        }
}]

此对象数组应易于排序。