简体   繁体   English

Array.sort 不会使用对象中的 NaN 值对数组进行重新排序

[英]Array.sort does not reorder array with NaN values in object

I have a simple case with reordering items in array by prop minLVL of each object in it.我有一个简单的案例,通过minLVL每个object的 prop minLVL重新排序数组中的项目。

But for some reason it works only if the previous and the next ones props are present (as you can see not each object has required minLVL field).但出于某种原因,它仅在存在上一个和下一个 props 时才有效(正如您所见,并非每个object都需要minLVL字段)。 So, if the minLVL is missing in some object it does not reoder such item to the bottom of the list, it just stay in the same position instead.因此,如果minLVL在某些对象缺少它不reoder这样的项目到列表的底部,它仅仅停留在相同的位置来代替。

How can I solve it?我该如何解决? Thanks谢谢

Example:例子:

 var h = [ { ID: 172 }, { ID: 179, minLVL: "30" }, { ID: 169 }, { ID: 173 }, { ID: 167, minLVL: "25" }, { ID: 175, minLVL: "10" } ] var n = h.sort((a, b) => Number(b.minLVL) - Number(a.minLVL)) console.log(n)

You can default those values to 0 if it does not exist inside the sort function:如果 sort 函数中不存在这些值,则可以将这些值默认为0

 var h = [{ ID: 172 }, { ID: 179, minCrimeLevel: "30" }, { ID: 169 }, { ID: 173 }, { ID: 167, minCrimeLevel: "25" }, { ID: 175, minCrimeLevel: "10" }] var n = h.sort((a, b) => (Number(b.minCrimeLevel) || 0) - (Number(a.minCrimeLevel)|| 0)) console.log(n)

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

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