提问者:小点点

按特定顺序排列数组


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

null

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);

null

无法将输出按[“未分类的潜在客户”,“保持/未分类”,“RGL”,“PGL”,“MGL”,“评估中的QO”,“到达”,“已确定的机会”,“BGL”,“返回营销”,“SGL”,“后续会议”,“第一次演示/会议”]排序


共2个答案

匿名用户

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

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

Mabe,您以一而不是零开始order对象的值,并使用默认值将未知值排序到所需的位置。

null

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);

匿名用户

请尝试下面的代码。

null

// 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);