简体   繁体   中英

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.

input.sort(func) => output

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

Output: ['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 . filter will return an array. 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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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