[英]How to sort strings in a pre decided order in Javascript?
我需要一个排序函数来按 b->c->a 的顺序对数组进行排序,而无需定义新数组。
input.sort(func) => 输出
输入:['b', 'b', 'c', 'c', 'a', 'c', 'b', 'a']
输出:['b', 'b', 'b', 'c', 'c', 'c', 'a', 'a']
传递一个类似于排序顺序的字符串数组。 现在使用forEach
迭代此参数并使用filter
过滤掉主数组中的元素。 filter
将返回一个数组。 将过滤后的数组中的元素推送到主数组。
var input = ['b', 'b', 'c', 'c', 'a', 'c', 'b', 'a'] function customSort(sortOrderArray) { var outPutArray = []; // iterate the input order array sortOrderArray.forEach(function(item) { // now from the original array filter out the elements which are matchin var m = input.filter(function(items) { return item === items }) // m will be an array // using spread operator & push this array to outPutArray outPutArray.push(...m) }) return outPutArray; } console.log(customSort(['b', 'c', 'a']))
尝试使用sort
:
var input = ['b', 'b', 'c', 'c', 'a', 'c', 'b', 'a'];
var order = ['b', 'c', 'a'];
input.sort((e1, e2) => order.indexOf(e1) - order.indexOf(e2))
// output: ['b', 'b', 'b', 'c', 'c', 'c', 'a', 'a']
d = {b:1,c:2,a:3} var result = ['b', 'b', 'c', 'c', 'a', 'c', 'b', 'a'].sort(function(v1,v2){ return d[v1]>d[v2]; }) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.