当你对数组进行排序时,可以这样说:
const arr = ["bad", "good", "all", "ugly"]
使用 arr.sort() 时,响应往往是:
arr = ["all", "bad", "good", "ugly"]
但是如果我需要自定义订购,例如:
arr = ["bad", "good", "ugly", "all"]
即为了示例,您需要将“all”元素推到排序数组的末尾而不是开头
我所做的是对数组进行排序,然后从数组中删除“所有”元素,然后将其添加到末尾,即
const a = _.pull(arr, "all");
a.splice(3, 0, "all")
console.log(a) // ["bad", "good", "ugly", "all"]
是否有更好或更简单的方法来做同样的事情?
最佳答案
您可以使用自定义比较器进行排序。类似的东西
[...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)))
关于javascript - 使用自定义顺序对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590563/