简体   繁体   English

如何在Javascript中以预先决定的顺序对字符串进行排序?

[英]How to sort strings in a pre decided order in Javascript?

I need a sorting function to sort an array with an order of b->c->a, without defining new array.我需要一个排序函数来按 b->c->a 的顺序对数组进行排序,而无需定义新数组。

input.sort(func) => output input.sort(func) => 输出

Input: ['b', 'b', 'c', 'c', 'a', 'c', 'b', 'a']输入:['b', 'b', 'c', 'c', 'a', 'c', 'b', 'a']

Output: ['b', 'b', 'b', 'c', 'c', 'c', 'a', 'a']输出:['b', 'b', 'b', 'c', 'c', 'c', 'a', 'a']

Pass an array of strings which will resemble the sort order.传递一个类似于排序顺序的字符串数组。 Now iterate this argument using forEach and use filter to filter out the elements from the main array .现在使用forEach迭代此参数并使用filter过滤掉主数组中的元素。 filter will return an array. filter将返回一个数组。 Push the elements from the filtered array to main array.将过滤后的数组中的元素推送到主数组。

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

Try using sort :尝试使用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.

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