javascript - 如何按照一定的规则设置数组的元素

标签 javascript arrays

假设我们有这样的数组:

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) 使用 includessuperWordsArray 时(其中 nsuperWords 中的单词数):

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 a Set object, using an approach that is, on average, quicker than testing most of the elements that have previously been added to the Set object. In particular, it is, on average, faster than the Array.prototype.includes method when an Array object has a length equal to a Set object's size.

关于javascript - 如何按照一定的规则设置数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72111221/

相关文章:

javascript - 带手动输入的 Jquery 范围 slider

javascript - 获取数组并将奇数和偶数插入单独的数组中

java - 列表内的数组

javascript - jQuery 事件未从我的 asp.net 控件触发

javascript - Javascript 和 PHP 中的字符串操作/编辑

javascript - “组件”不能用作 JSX 组件。下一页

javascript - 如何忽略 React Router 中的链接?

c++ - 如何交换数组元素以将数组从类列转换为类行表示

python - 如何在Python中将二维数组添加到数据库中

Java 数组问题