我需要带有Bustype和index的排序数组
我所拥有的
[
{ BusType: "SATA", index: 1, Id: "SATA.1" },
{ BusType: "SATA", index: 10, Id: "SATA.10" },
{ BusType: "IDE", index: 1, Id: "IDE.1" },
{ BusType: "IDE", index: 2, Id: "IDE.2" },
{ BusType: "IDE", index: 10, Id: "IDE.10" },
]预期产出:
[
{ BusType: "IDE", index: 1, Id: "IDE.1" },
{ BusType: "IDE", index: 2, Id: "IDE.2" },
{ BusType: "IDE", index: 10, Id: "IDE.10" },
{ BusType: "SATA", index: 1, Id: "SATA.1" },
{ BusType: "SATA", index: 10, Id: "SATA.10" }
]我试过这个:
arr.sort((a, b) => a.Id.localeCompare(b.Id))但得到了这个:
[
{ BusType: "IDE", index: 1, Id: "IDE.1" },
{ BusType: "IDE", index: 10, Id: "IDE.10" },
{ BusType: "IDE", index: 2, Id: "IDE.2" },
{ BusType: "SATA", index: 1, Id: "SATA.1" },
{ BusType: "SATA", index: 10, Id: "SATA.10" }
]像字母一样排序..。1 10 100 2 20 3
如何分类正确?
发布于 2020-07-28 19:30:51
arr.sort((a, b) => a.BustType.localeCompare(b.BustType) || a.index - b.index);它将按BustType进行排序,如果返回0 (意味着它们具有相同的BusType),则||的右侧将进入,而a.index - b.index将由index进行排序。这叫做。
发布于 2020-07-28 19:47:49
你可以实现一个多类型的。
你只需要声明一些分类器。这些只是告诉您的字段的排序函数的一种方法,例如,要排序的类型和方向。
下面是一个分类器示例:
/**
* @param {String} name - Object field to be compared
* @param {String=['string'],'int'} type - Value type
* @param {String=['asc'],'desc'} dir - Sort direction
* @param {Function} fn - Optional comparator function
*/
const exampleSorter = {
name : 'field',
type : 'string',
dir : 'asc'
fn : (a, b) => a - b
}分类器可以是:
演示
const busData = [
{ BusType: "SATA" , index: 1 , Id: "SATA.1" },
{ BusType: "SATA" , index: 10 , Id: "SATA.10" },
{ BusType: "IDE" , index: 1 , Id: "IDE.1" },
{ BusType: "IDE" , index: 2 , Id: "IDE.2" },
{ BusType: "IDE" , index: 10 , Id: "IDE.10" },
]
const multiSort = (data, sorters) => {
const defaultSorter = { type: 'string', dir: 'asc' }
const compare = (a, b, sorter) => {
let field = sorter.name
if (b == null || b[field] == null) return -1
if (a == null || a[field] == null) return 1
if (sorter.fn) return sorter.fn.call(sorter, a[field], b[field])
switch (sorter.type) {
case 'int': return a[field] - b[field];
case 'string':
default: return a[field].localeCompare(b[field])
}
}
if (typeof sorters === 'string') sorters = [sorters]
sorters = sorters.map(sorter => typeof sorter === 'string'
? { ...defaultSorter, name: sorter }
: { ...defaultSorter, sorter })
return data.sort((a, b) => {
for (let i = 0; i < sorters.length; i++) {
let sorter = sorters[i], result = compare(a, b, sorter)
if (result !== 0) return result * (sorter.dir === 'desc' ? -1 : 1)
}
return 0
})
}
console.log(multiSort(busData, [
{ name: 'BusType', fn: (a, b) => a.localeCompare(b) },
{ name: 'index', type: 'int', dir: 'asc' }
])).as-console-wrapper { top: 0; max-height: 100% !important; }
发布于 2020-07-28 23:12:39
试试这个:
arr.sort(
(a,b)=> {
a.BusType<b.BusType?-1:
a.BusType>b.BusType?1:
a.index<b.index?-1:
a.index>b.index?1:
0;
}
);我们比较BusType,如果a's较小,则为-1,如果a's较大,则为1,如果等于:
我们比较index,如果a's较小,则为-1,如果a's较大,则为: 0。
https://stackoverflow.com/questions/63141351
复制相似问题