按整数属性值对数组中的对象进行排序 [英] Sorting of objects in an array by integer property value
问题描述
有一个看起来像这样的数组:
There is an array which looks like this:
[
{
_id: 'xxnQt5X8pfbcJMn6i',
order: 2
},
{
_id: 'X8pfbcJxxnQt5Mn6i',
order: 1
},
{
_id: 'Qt5X8pfxxnbcJMn6i',
order: 3
}
]
现在,我需要按 order
值对该数组的对象进行排序.我尝试这样做:
Now I need to sort the objects of this array by the order
value. I tried to do this:
array.sort((a, b) => {
return (a.order > b.order)
? 1
: (b.order > a.order)
? -1
: 0
})
但是首先,对于我来说,仅按整数值进行排序看起来有些复杂,其次,它给了我错误 TypeError:无法分配为仅读取对象'[object Array]'的属性'1'/code>
But first it looks to me a bit to complicated for just sorting by an integer value and second it gives me the error TypeError: Cannot assign to read only property '1' of object '[object Array]'
推荐答案
This can be achieved using Array.prototype.sort, no need for the further return conditions on the ternary operator, the array will implicitly be sorted by the first comparison:
console.log([
{
_id: 'xxnQt5X8pfbcJMn6i',
order: 2
},
{
_id: 'X8pfbcJxxnQt5Mn6i',
order: 1
},
{
_id: 'Qt5X8pfxxnbcJMn6i',
order: 3
}
].sort((a, b) => a.order - b.order))
尽管使用提供的示例,我无法重现您得到的错误.
I can't reproduce the error that you're getting using the example provided though.
这篇关于按整数属性值对数组中的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!