【问题标题】:order the array in specific order按特定顺序排列数组
【发布时间】:2020-06-15 13:23:57
【问题描述】:

我有一个数组,想按特定顺序对数组进行排序

var orderedObj = {
  "1st Presentation / Meeting": 0,
  "Follow-On Meetings": 1,
  "Hold\/Uncategorized": 2,
  "MGL": 3,
  "PGL": 4,
  "BGL": 5,
  "RGL": 6,
  "SGL": 7,
  "Uncategorized Leads": 8,
  "Identified Opportunities": 9,
  "QO under evaluation": 10
};

const typobj = ["Uncategorized lead", "Hold/Uncategorized", "RGL", "PGL", "MGL", "QO under evaluation", "Reaches", "Identified Opportunities", "BGL", "Back to marketing", "SGL", "Follow-On Meetings", "1st Presentation / Meeting"];

var typesOrd = typobj.sort((a, b) => orderedObj[a.label] - orderedObj[b.label]);
console.log(typesOrd);

无法按照["Uncategorized lead", "Hold/Uncategorized", "RGL", "PGL", "MGL", "QO under evaluation", "Reaches", "Identified Opportunities", "BGL", "Back to marketing", "SGL", "Follow-On Meetings", "1st Presentation / Meeting"]的输出顺序排序

【问题讨论】:

  • 真的有必要吗,我不会重新排序对象,
  • 也许我可以将订单保存在数组或json中
  • 删除label 部分。 a 是单个数组项。只需orderedObj[a] 为您提供每个项目的优先级值
  • 我已经给你一个答案@user3386779

标签: javascript html jquery arrays


【解决方案1】:

您需要直接取值并注意拼写。

排序对给定数组进行排序。

您可能会从 1 而不是 0 开始 order 对象的值,并使用默认值将未知值排序到所需位置。

var orderedObj = {
  "1st Presentation / Meeting": 0,
  "Follow-On Meetings": 1,
  "Hold\/Uncategorized": 2,
  "MGL": 3,
  "PGL": 4,
  "BGL": 5,
  "RGL": 6,
  "SGL": 7,
  "Uncategorized Leads": 8,
  "Identified Opportunities": 9,
  "QO under evaluation": 10
};
const typobj = ["Uncategorized Leads", "Hold/Uncategorized", "RGL", "PGL", "MGL", "QO under evaluation", "Reaches", "Identified Opportunities", "BGL", "Back to marketing", "SGL", "Follow-On Meetings", "1st Presentation / Meeting"];

typobj.sort((a, b) => orderedObj[a] - orderedObj[b]);

console.log(typobj);

【讨论】:

    【解决方案2】:

    试试下面的代码。

    // RAW
    var orderedObj = {
      "1st Presentation / Meeting": 0,
      "Follow-On Meetings": 1,
      "Hold\/Uncategorized": 2,
      "MGL": 3,
      "PGL": 4,
      "BGL": 5,
      "RGL": 6,
      "SGL": 7,
      "Uncategorized Leads": 8,
      "Identified Opportunities": 9,
      "QO under evaluation": 10
    };
    //Target order
    const typobj = ["Uncategorized Leads", "Hold/Uncategorized", "RGL", "PGL", "MGL", "QO under evaluation", "Reaches", "Identified Opportunities", "BGL", "Back to marketing", "SGL", "Follow-On Meetings", "1st Presentation / Meeting"];
    
    var new_obb={};
    typobj.forEach(function(item){
    new_obb[item]=orderedObj[item];
    });
    
    // Final Output
    console.log(new_obb);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 2019-10-10
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多