javascript - javascript使用定制排序对字符串的array 排序

  显示原文与译文双语对照的内容

当你对 array 进行排序时,请执行以下操作:


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



使用 arr.sort(),响应往往是:


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



但是如果我需要定制排序,如:


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



为了示例,你需要将元素推到排序的array的末尾,而不是开始

我做的是对 array 进行排序,然后从 array 中删除"全部"元素,只将它的添加到最终 IE 中


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)))

你可以使用运算符执行类似的操作:


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



arr.sort((a, b) => (a =="all") - (b =="all") || a.localeCompare(b))



console.log(arr)

减法布尔值返回一个数字( true - false === 1 ) 。如果一个字符串是 "all",它将不会检查第二个条件。

我认为 below 一个是空闲的那个。 因为在排序时,你可以把"全部"拉到末尾


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)



使用自定义排序函数并对 'all' 字符串进行不同的处理。


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



//return 0 if both are all or if one of them is all then return based on order needed


//if both are not all then compare the string


arr.sort((a, b) => a === 'all'? (b === 'all'? 0 : 1) : (b === 'all'? -1 : a.localeCompare(b)))



console.log(arr)
...