I have 3 items in an array and each of those items have a property called distanceFromUser
which is just a number
. Two of those objects have undefined
for that property.
If I run items.sort((a,b) => a.distanceFromUser - b.distanceFromUser);
the two object with undefined
or null
get put first in the array. How can I get them to go in the back of the array?
Just modify your compare function accordingly. See below. Note that I used == null
which also checks for undefined (while ===
would not). Other proposed solutions using the or operator ( a.distanceFromUser || ...
) or similar are also considerable, but error-prone if distanceFromUser is 0.
let items = [ { distanceFromUser: 1 }, { distanceFromUser: 23 }, { distanceFromUser: undefined }, { distanceFromUser: 12 }, { distanceFromUser: 2 }, { distanceFromUser: 9 }, { distanceFromUser: null }, ]; items.sort((a, b) => { if (b.distanceFromUser == null) return -1; if (a.distanceFromUser == null) return 1; return b.distanceFromUser - a.distanceFromUser; }); console.log(items);
You could check the values for undefined
or null
and sort them to the end of the array, while perserving the order of the distance with a chained approach.
var items = [{ id: 1, distanceFromUser: undefined }, { id: 2, distanceFromUser: 1 }, { id: 3, distanceFromUser: 2 }, { id: 4, distanceFromUser: 5 }, { id: 5, distanceFromUser: 1 }, { id: 6, distanceFromUser: undefined }, { id: 7, distanceFromUser: null }, { id: 8, distanceFromUser: null }]; items.sort( (a, b) => (a.distanceFromUser === undefined || a.distanceFromUser === null) - (b.distanceFromUser === undefined || b.distanceFromUser === null) || a.distanceFromUser - b.distanceFromUser ); console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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.