简体   繁体   English

使用自定义顺序对字符串数组进行排序

[英]Sorting an array of strings with custom ordering

When you sort an array lets say: 对数组进行排序时,请说:

const arr = ["bad", "good", "all", "ugly"]

with arr.sort() the response tends to be: 使用arr.sort()时,响应趋向于:

arr = ["all", "bad", "good", "ugly"]

but what if I need custom ordering such as: 但是如果我需要自定义订购,例如:

arr = ["bad", "good", "ugly", "all"]

ie for the sake of the example you need to push the "all" element to the end of the sorted array instead of the start 即,为了示例,您需要将“ all”元素推到排序数组的末尾而不是开始

What I did was to sort the array and then removed the "all" element from the array only to add it in the end ie 我所做的是对数组进行排序,然后从数组中删除“所有”元素,仅在最后添加它,即

const a = _.pull(arr, "all");
a.splice(3, 0, "all")
console.log(a)     // ["bad", "good", "ugly", "all"]

Is there a better or a less complex way of doing the same? 是否有更好或更简单的方法?

You can use custom comparator for sorting. 您可以使用自定义比较器进行排序。 Something like 就像是

[...arr].sort((x, y) => x === 'all' ? 1 : y === 'all' ? -1 : x.localeCompare(y))

 const arr = ["bad", "good", "all", "ugly"]; console.log([...arr].sort((x, y) => x === 'all' ? 1 : y === 'all' ? -1 : x.localeCompare(y))) 

You could do something like this using the OR operator: 您可以使用OR运算符执行以下操作:

 let arr = ["all", "bad", "all", "good", "ugly"] arr.sort((a, b) => (a == "all") - (b == "all") || a.localeCompare(b)) console.log(arr) 

Subtracting booleans returns a number ( true - false === 1 ). 减去布尔值将返回一个数字( true - false === 1 )。 If one the strings is "all" , it won't check the second condition at all. 如果一个字符串是"all" ,它将根本不会检查第二个条件。

i think below one is the idle one. 我认为下面是一个闲置的。 Because while sorting itself you can pull the "all" to the end 因为在排序时,您可以将“全部”拉到最后

let list = ["all", "bad", "good", "ugly"]
list.sort((a, b) => {
    if(a === 'all') {return 1;}
    if(b === 'all') {return -1;}
    if(a < b) { return -1; }
    if(a > b) { return 1; }
    return 0
})
console.log(list)

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

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