简体   繁体   English

如何按这些字符串的一部分对字符串进行排序?

[英]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".每个对象都有一个 id,它看起来像这样:“Device/1”或“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?我知道可以通过例如自己实现冒泡排序来实现,但是使用 javascript sort() 方法是否可以实现我的目标?

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() :您可以将排序函数传递给.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...如果您的id一致,则不需要任何拆分...

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

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