假设我们有这样的数组:
const words = ['luigi', 'Bar', 'Test', 'zac1', 'Alf0'];
现在我想按字母顺序对这个数组进行排序:
words.sort((a, b) => a.localeCompare(b));
假设我们有一组 super 词。此词具有高优先级,应位于“词列表”的顶部。
const superWords = ["zac1", "Test"]
因此 words 数组的期望结果将是:
const desiredResult = ["Test", "zac1","Alf0", "Bar", "luigi"]
我该怎么做?
最佳答案
您可以将 superWords
转换为 Set O(1)
查找时间使用 has
而不是 O(n)
使用 includes
当 superWords
是 Array 时(其中 n
是 superWords
中的单词数):
const words = ['luigi', 'Bar', 'Test', 'zac1', 'Alf0'];
const superWords = ['zac1', 'Test'];
const superWordsSet = new Set(superWords); // This is O(n) but you only need to do this once.
words.sort((a, b) => {
if (superWordsSet.has(a) && !superWordsSet.has(b)) {
return -1;
} else if (!superWordsSet.has(a) && superWordsSet.has(b)) {
return 1;
}
return a.localeCompare(b);
});
console.log(words);
Performance
The
Set
has
method checks if a value is in aSet
object, using an approach that is, on average, quicker than testing most of the elements that have previously been added to theSet
object. In particular, it is, on average, faster than theArray.prototype.includes
method when anArray
object has alength
equal to aSet
object'ssize
.
关于javascript - 如何按照一定的规则设置数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72111221/