Home  >  Q&A  >  body text

JavaScript two-dimensional array sorting problem

[['10','8'],['11','4'],['18','7'],['7','6'],['8','7'],['9','5']]

JavaScript How to make an array like this
[['7','6'],['8','7'],['9','5'],['10',' 8'],['11','4'],['18','7']]
In this order

大神

仅有的幸福仅有的幸福2686 days ago721

reply all(4)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-06-12 09:29:27

    array = [['10','8'],['11','4'],['18','7'],['7','6'],['8',' 7'],['9','5']]
    function sortNumber(a,b){return a[0]-b[0]}
    let newArray = array.sort(sortNumber)

    newArray should be the result you want

    reply
    0
  • 代言

    代言2017-06-12 09:29:27

    var arr = [['10','8'],['11','4'],['18','7'],['7','6'],['8','7'],['9','5']]
    arr.sort(function(a, b) {
        return a[0]-b[0]
    })

    reply
    0
  • PHP中文网

    PHP中文网2017-06-12 09:29:27

    The result of the arrangement of your two-dimensional array seems to be compared with the first subscripted element in each element in the array (array). Then it would be bad if it were converted into a one-dimensional array and sorted. ? The one-dimensional array is sorted, and then the original two-dimensional array is sorted using index to correspond to the previous one-dimensional array.
    Logical implementation idea:
    var twoArray = [['10','8'],['11','4'],['18','7'],['7','6'], ['8','7'],['9','5']];

        var oneArray = [];
        twoArray.map(function (item ,index) {
            oneArray.push({value: item[0], index: index});
        });
        console.log(oneArray);
        function sortNumber (a, b) {
            return a.value - b.value;
        }
        console.log(oneArray.sort(sortNumber));
        // 此时的oneArray已排好序
        var newTwoArray = [];
        oneArray.map(function (item) {
            newTwoArray.push(twoArray[item.index]);
        });
        console.log(newTwoArray);// 即你要的排序

    reply
    0
  • 黄舟

    黄舟2017-06-12 09:29:27

    var groupNum = 3;
    
    var arr1 = [['10','8'],['11','4'],['18','7'],['7','6'],['8','7'],['9','5']];
    
    var arr2 = [];
    
    for (var i = arr1.length; i > 0 ; i -= groupNum) {
      arr2.push(arr1.slice(i - groupNum, i));
    }
    
    console.log(arr2) // [['7','6'],['8','7'],['9','5'],['10','8'],['11','4'],['18','7']]

    reply
    0
  • Cancelreply