简体   繁体   中英

How to use JS Array.sort() with objects with different properties

So I have these Objects:

let obj1 = { from: Date, to: Date }
let obj2 = { date: Date }

They are in an Array:

let arr = [ obj1, obj2 ]

Now I want to sort the objects inside the array with arr.sort(). But I can't figure out how to use the property "from" for the object that has this property OR "date" for the other... I think there's an easy solution to that but I can't find anything related to this.

 let obj1 = { from: new Date(345635), to: new Date(454567) } let obj2 = { date: new Date(1230464) } let arr = [ obj1, obj2 ]; const sorted = arr.sort((a, b) => ((a.from || a.date) - (b.from || b.date))) console.log(sorted)

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