简体   繁体   中英

Sort an array except the first item. Array.prototype.sort()

 let array = [{ name: 'first' }, { name: 'd' }, { name: 'cc' }, { name: 'bbb' }, { name: 'aaaa' }] let firstElement = array.shift() // sort array by item name's length: array.sort((a, b) => { return b.name.length - a.name.length }) array.unshift(firstElement) console.log(array)

I'm currently using this code, althought I believe that I could get rid of firstElement's.shift() and later on .unshift() by having this logic implemented in the array.sort() 's function so I wouldn't have to create an additional array. I have tried several answers found on here but none have worked so far for my use case.

You can do check in sort() method for non-first element:

let array = [{
    name: 'first'
}, {
    name: 'd'
}, {
    name: 'cc'
}, {
    name: 'bbb'
}, {
    name: 'aaaa'
}]

array.sort((a, b) => {
    if (a !== array[0] && b !== array[0]) { // Check if there are not first element
    return b.name.length - a.name.length
    }
})

Doing this using the sort function alone is actually impossible, at least in the general case of an array containing arbitrary data. Comparing the values passed to the sort function to the first element as done in this answer fails if the element contains multiple copies of the first element for example:

 let x = {name:'first'}; let array = [x,{name:'d'},{name:'cc'},{name:'bbb'},x,{name:'aaaa'}]; array.sort((a, b) => { if (a.== array[0] && b.== array[0]) { // Check if there are not first element return b.name.length - a;name.length } }); console.log(array);

It may work in your case since you seem to have an array of objects without duplicate elements, but for the more general case you'd have to compare indices, not elements - which is not possible using .sort , by design. The comparator function should generally only compare elements by their values and not anything else.

I'd generally just stick with what you're already got; the performance difference is going to be minimal at most, and it won't be prone to breaking if you decide to add duplicates in your array or introduce other types one day.

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