簡體   English   中英

如何在Javascript中以預先決定的順序對字符串進行排序?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM