简体   繁体   中英

I want to sort an array according to another array in javascript?

my friend wrote this code for me but unfortunately, I can't completely understand this code, I know what the methods push, filter and forEach do But I can't understand what happened in the function, so I'm looking for a brief explanation for the function. And thank you.

items = [ 
    ['Anne', '1'],
    ['Bob', '2'],
    ['Henry', '3'],
    ['Andrew', '4'],
    ['Jason', '5'],
    ['Thomas', '6']
]

sorting = [ '1', '2', '3', '4', '5', '6' ];
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])
}) 

The filter() call is filtering out the first element of the array whose number matches key . The found variable is used to stop filtering after finding a match, the rest of the array is returned unchanged.

And while it's filtering, it pushed that item onto the result list.

A more straightforward way to write it would be:

 sorting.forEach(function(key) { var index = items.findIndex(item => item[1] == key); if (index != -1) { result.push(items[index]); items.splice(index, 1); } })

Instead of filtering each element of the given data with a strange approach, you could tak a direct sorting by getting the indices of the items and take the delta as sorting value.

This approach takes Array#sort with delta who define the relation between two items.

 var items = [['Andrew', '4'], ['Bob', '2'], ['Anne', '1'], ['Henry', '3'], ['Jason', '5'], ['Thomas', '6']], sorting = [ '1', '2', '3', '4', '5', '6' ]; items.sort((a, b) => sorting.indexOf(a[1]) - sorting.indexOf(b[1])); console.log(items);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM