【问题标题】:Sort Element of array on the basis of another array in lexical order by using just sort function仅使用 sort 函数根据另一个数组按词法顺序对数组的元素进行排序
【发布时间】:2021-08-28 10:50:35
【问题描述】:

假设我们有两个数组参数和顺序,我想将顺序数组元素放在第一位,并将结果中所有其他元素的排序顺序。

我不想在排序过程中使用 order 数组。 也想用排序功能。

let parameter = ['Door', 'fjjfh','Container Number','jdjfr', 'Cases', 'hello', "hi", 'Items/sort']

let order = ['Door', 'Container Number', 'Cases', 'Items/sort']

Output ->['Door', 'Container Number', 'Cases', 'Items/sort','fjjfh','hello','hi','jdjfr']

【问题讨论】:

  • 您希望order 数组元素按什么顺序排列?它们在原始数组中的顺序,或order?
  • 和给出的一样

标签: javascript sorting data-structures


【解决方案1】:

您需要检查每个被排序的项目是否在order 数组中,并优先考虑其中的一项(或者如果它们都在,则优先考虑它们的相对位置),请参阅 cmets:

let parameter = ['Door', 'fjjfh','Container Number','jdjfr', 'Cases', 'hello', "hi", 'Items/sort'];
let order = ['Door', 'Container Number', 'Cases', 'Items/sort'];

// Wanted: ["Door", "Container Number", "Cases", "Items/sort","fjjfh","hello","hi","jdjfr"]

parameter.sort((a, b) => {
    const apos = order.indexOf(a);
    const bpos = order.indexOf(b);
    if (apos !== -1) {
        // `a` is in the `order` array
        if (bpos === -1) {
            // `b` isn't, put `a` first
            return -1;
        }
        // Both are, put them in the order they have in `order`
        return apos - bpos;
    } else if (bpos !== -1) {
        // `b` is in the `order` array, `a` isn't; `b` comes first
        return 1;
    } else {
        // Neither is in the `order` array, put them in lexicographical order
        return a.localeCompare(b);
    }
});
console.log(parameter);

如果您以这种方式对 真正大量 数组进行排序和/或如果 order真正大量,您可能需要创建一个 map 的位置在order 开始之前,您不必为每个位置查找线性遍历order

let parameter = ['Door', 'fjjfh','Container Number','jdjfr', 'Cases', 'hello', "hi", 'Items/sort'];
let order = ['Door', 'Container Number', 'Cases', 'Items/sort'];

// Wanted: ["Door", "Container Number", "Cases", "Items/sort","fjjfh","hello","hi","jdjfr"]

const orderMap = new Map(order.map((value, index) => [value, index]));
parameter.sort((a, b) => {
    const apos = orderMap.get(a);
    const bpos = orderMap.get(b);
    if (apos !== undefined) {
        // `a` is in the `order` array
        if (bpos === undefined) {
            // `b` isn't, put `a` first
            return -1;
        }
        // Both are, put them in the order they have in `order`
        return apos - bpos;
    } else if (bpos !== undefined) {
        // `b` is in the `order` array, `a` isn't; `b` comes first
        return 1;
    } else {
        // Neither is in the `order` array, put them in lexicographical order
        return a.localeCompare(b);
    }
});
console.log(parameter);

但您不必为中小型数组而烦恼。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2013-11-10
    • 1970-01-01
    • 2019-08-04
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多