简体   繁体   English

对除第一项之外的数组进行排序。 Array.prototype.sort()

[英]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.我目前正在使用这段代码,虽然我相信我可以通过在 array.sort array.sort()的 function 中实现这个逻辑来摆脱firstElement's.shift()和后来的.unshift() () 所以我不会创建一个额外的数组。 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:您可以检查非第一个元素的 sort() 方法:

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.单独使用排序 function 实际上是不可能的,至少在包含任意数据的数组的一般情况下。 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:如果元素包含第一个元素的多个副本,则将传递给排序 function 的值与此答案中的第一个元素进行比较失败,例如:

 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.它可能适用于您的情况,因为您似乎有一个没有重复元素的对象数组,但对于更一般的情况,您必须比较索引,而不是元素 - 这是不可能使用.sort设计的。 The comparator function should generally only compare elements by their values and not anything else.比较器 function 通常应该只比较元素的值,而不是其他任何东西。

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.性能差异最多将是最小的,如果您决定有一天在数组中添加重复项或引入其他类型,它不会容易中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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