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

anu*_*ysh 0 javascript arrays sorting

对数组进行排序时,请说:

const arr = ["bad", "good", "all", "ugly"]
Run Code Online (Sandbox Code Playgroud)

使用arr.sort()时,响应趋向于:

arr = ["all", "bad", "good", "ugly"]
Run Code Online (Sandbox Code Playgroud)

但是如果我需要自定义订购,例如:

arr = ["bad", "good", "ugly", "all"]
Run Code Online (Sandbox Code Playgroud)

即,为了示例,您需要将“ all”元素推到排序数组的末尾而不是开始

我所做的是对数组进行排序,然后从数组中删除“所有”元素,仅在最后添加它,即

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

是否有更好或更简单的方法?

mbo*_*jko 5

您可以使用自定义比较器进行排序。就像是

[...arr].sort((x, y) => x === 'all' ? 1 : y === 'all' ? -1 : x.localeCompare(y))
Run Code Online (Sandbox Code Playgroud)

[...arr].sort((x, y) => x === 'all' ? 1 : y === 'all' ? -1 : x.localeCompare(y))
Run Code Online (Sandbox Code Playgroud)