前端表单字段展示排序?

假定表单数据 origin

const orignal = [
    { dbName: "STATUS", ... },
    { dbName: "NAME", ... },
    { dbName: "DEPART", ... },
    ...
]

现要将 origin 按如下优先级,针对 dbName 字段进行排序显示

"NAME", "AGE", "LEVEL", "CODE", "DEPART", "NUMBER", "STATUS"
const ruleSort = ["NAME", "AGE", "LEVEL", "CODE", "DEPART", "NUMBER", "STATUS"];

const devCardInfo = origin.sort(({ dbName: dbNameA }, { dbName: dbNameB }) => {
    const iA = ruleSort.indexOf(dbNameA.toUpperCase());
    const iB = ruleSort.indexOf(dbNameB.toUpperCase());

    if (iA === iB) return 0;
    if (iA === -1) return 1;
    if (iB === -1) return -1;

    return iA - iB;
  });

有没有更成熟的方案?


不好意思我没有表达清楚,补充一下:
ruleSort中提及的字段并不完整,

  1. 未提及的字段照常显示(无需在意排序)
  2. 提及的字段也不一定全部存在
  3. 不会有重复的 dbName
阅读 2.1k
4 个回答

这样?

const ruleSort = ["NAME", "AGE", "LEVEL", "CODE", "DEPART", "NUMBER", "STATUS"];
const origin = [
    { dbName: "STATUS", },
    { dbName: "NAME", },
    { dbName: "DEPART",},
    { dbName: "any",},
    { dbName: "NUMBER",},
]
// i+1是因为下面的||运算符,如果使用??可以直接设置为i
const indexes = ruleSort.reduce((res,k,i) => (res[k] = i+1, res),{})
const devCardInfo = origin.sort(({ dbName: n1 }, { dbName: n2 }) => (indexes[n1]||Infinity) - (indexes[n2]||Infinity));
let inList = []
let notInList = []

original.forEach(item => {
  let index = ruleSort.findIndex(dbName => dbName === item.dbName)
  
  if (index < 0) {
    notInList.push(item)
    return
  }
  
  inList[index] = item
})

let resultList = inList.filter(r => !!r).concat(notInList)
  const orignal = [
    { dbName: "STATUS" },
    { dbName: "NAME" },
    { dbName: "DEPART" },
  ];

  const ruleSort = [
    "NAME",
    "AGE",
    "LEVEL",
    "CODE",
    "DEPART",
    "NUMBER",
    "STATUS",
  ];

  console.log(
    ruleSort
      .map((e) => orignal.find(({ dbName }) => dbName === e))
      .filter((e) => e)
  );

集合操作,不需要排序,就是费点内存。。。

const original = [
  { dnName: 'no' },
  { dnName: 'need' },
  { dnName: 'sort' },
  { dbName: 'order_2' },
  { dbName: 'order_3' },
  { dbName: 'order_1' },
];

const ruleSort = ['order_1', 'order_2', 'order_3', 'not_exist'];

const orderSet = new Set(ruleSort);
const nameToItem = new Map(original.map((v) => [v.dbName, v])); 

const prefix = ruleSort
  .filter((v) => nameToItem.has(v))
  .map((t) => nameToItem.get(t));
const postfix = original.filter((v) => !orderSet.has(v.dbName));

console.log([...prefix, ...postfix]);
// [
//   { dbName: 'order_1' },
//   { dbName: 'order_2' },
//   { dbName: 'order_3' },
//   { dnName: 'no' },
//   { dnName: 'need' },
//   { dnName: 'sort' }
// ]
推荐问题
宣传栏