我只是想从数组中按字母顺序按第一个字母排序,然后根据我给定的模式按第二个字母排序,该模式与第一个字母匹配



♦e、b, c, d, f, g, h, o, j, k, l, m, n, u, p, q, r, s, t, v, w, x, y, z

我想按照字母顺序对arr中的单词进行排序,先按第一个字母排序,然后按与第一个字母匹配的相似单词的第二个字母排序。

[‘aobcdh’,‘aibcdh’,‘aabcdh’,‘aacbdh’,‘cfghjd ', ' cighjd ']

♦输出应该是:

[‘aibcdh’,‘aobcdh’,‘aabcdh’,‘aacbdh’,‘cighjd ', ' cfghjd ']

♦或: aibcdhaobcdhaabcdhaacbdhcighjdcfghjd

My Code here:

let pattern = ['e', 'b', 'c', 'd', 'i', 'f', 'g', 'h', 'o', 'j', 'k', 'l', 'm', 'n', 'u', 'p', 'q', 'r', 's', 't', 'a', 'v', 'w', 'x', 'y', 'z']
let arr = ['aobcdh', 'aibcdh', 'aabcdh', 'aacbdh', 'cfghjd', 'cighjd']
let arrSorted = arr.sort() //Natural sorting
console.log(arrSorted)
// output in array
const newArr = arrSorted.sort((a, b) => pattern.indexOf(a[1]) - pattern.indexOf(b[1]))
console.log(newArr) //Sorted by its 2nd character with given pattern
// single output without array
for (let i = 0; i < pattern.length; i++) {
for (let j = 0; j < arrSorted.length; j++) {
if (pattern[i] === arrSorted[j][1]) {
console.log(arrSorted[j]) //Sorted by its 2nd character with given pattern
}
}
}

第一个可以按字符串排序,第二个按自定义值排序。

const
pattern = 'ebcdifghojklmnupqrstavwxyz',
array = ['aobcdh', 'aibcdh', 'aabcdh', 'aacbdh', 'cfghjd', 'cighjd'],
order = Object.fromEntries(Array.from(pattern, (l, i) => [l, i + 1]));
array.sort((a, b) =>
a[0].localeCompare(b[0]) ||
order[a[1]] - order[b[1]]
);
console.log(array);

最新更新