Javascript - sort array based on another array

后端 未结 22 1447
鱼传尺愫
鱼传尺愫 2020-11-22 03:45

Is it possible to sort and rearrange an array that looks like this:

itemsArray = [ 
    [\'Anne\', \'a\'],
    [\'Bob\', \'b\'],
    [\'Henry\', \'b\'],
             


        
22条回答
  •  名媛妹妹
    2020-11-22 04:19

    Something like:

    items = [ 
        ['Anne', 'a'],
        ['Bob', 'b'],
        ['Henry', 'b'],
        ['Andrew', 'd'],
        ['Jason', 'c'],
        ['Thomas', 'b']
    ]
    
    sorting = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
    result = []
    
    sorting.forEach(function(key) {
        var found = false;
        items = items.filter(function(item) {
            if(!found && item[1] == key) {
                result.push(item);
                found = true;
                return false;
            } else 
                return true;
        })
    })
    
    result.forEach(function(item) {
        document.writeln(item[0]) /// Bob Jason Henry Thomas Andrew
    })
    

    Here's a shorter code, but it destroys the sorting array:

    result = items.map(function(item) {
        var n = sorting.indexOf(item[1]);
        sorting[n] = '';
        return [n, item]
    }).sort().map(function(j) { return j[1] })
    

提交回复
热议问题