简体   繁体   中英

How to sort strings by part of these strings?

I have got an array of objects. Every object has an id, which looks something like this: "Device/1" or "Device/7". In my case the array that I receive is unsorted and I am trying to sort it by the number after the "/". I know it is possible by implementing a bubble sort for example by myself, but is it possible to achieve my goal using the javascript sort() method?

This should do the work :)

 let arr = [{ id: 'Device/2' }, { id: 'Device/1' }] arr.sort((a, b) => parseInt(a.id.split('/')[1]) - parseInt(b.id.split('/')[1])) console.log(arr)

You can pass a sort function to .sort() :

 const arr = [ {id: 'Device/7'}, {id: 'Device/3'}, {id: 'Device/1'}, {id: 'Device/5'}, ]; console.log(arr.sort((a,b) => a.id.localeCompare(b.id)));

if your id s are consistent you do not need any splitting...

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