简体   繁体   中英

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.

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). 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.

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:

 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)

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