按自定义顺序对对象数组进行排序

时间:2018-04-25 17:53:05

标签: javascript angularjs underscore.js

我有一个对象数组,它们有一个名为'CODE'的属性。

[
  {
   ID: 168,
   NAME: "First name",
   CODE: "AD"
  },
  {
   ID: 167,
   NAME: "Second name",
   CODE: "CC"
  },
  {
   ID: 169,
   NAME: "Third name",
   CODE: "CCM"
  },
  {
   ID: 170,
   NAME: "Fourth name",
   CODE: "CR"
  },
]

如何通过自定义订单订购阵列,如:

var item_order = ["CCM","CR","AD","CC"];

尝试各种方法但没有成功。请帮忙。

5 个答案:

答案 0 :(得分:6)

您可以将函数sort与函数indexOf一起使用。



var array = [  {   ID: 168,   NAME: "First name",   CODE: "AD"  },  {   ID: 167,   NAME: "Second name",   CODE: "CC"  },  {   ID: 169,   NAME: "Third name",   CODE: "CCM"  },  {   ID: 170,   NAME: "Fourth name",   CODE: "CR"  }],
    item_order = ["CCM","CR","AD","CC"];

array.sort((a, b) => item_order.indexOf(a.CODE) - item_order.indexOf(b.CODE));

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:4)

对于大型数组,我建议使用一个对象作为索引。



var array = [{ ID: 168, NAME: "First name", CODE: "AD" }, { ID: 167, NAME: "Second name", CODE: "CC" }, { ID: 169, NAME: "Third name", CODE: "CCM" }, { ID: 170, NAME: "Fourth name", CODE: "CR" }],
    item_order = ["CCM", "CR", "AD", "CC"],
    order = item_order.reduce((r, k, v) => Object.assign(r, { [k]: v }), {});

array.sort((a, b) => order[a.CODE] - order[b.CODE]);

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:1)

您将使用array.sort(customSort),其中:

function customSort(a,b)
{
    a = item_order.indexOf(a.CODE);
    b = item_order.indexOf(b.CODE);

    return a - b;
}

答案 3 :(得分:1)



var array = [
  {
   ID: 168,
   NAME: "First name",
   CODE: "AD"
  },
  {
   ID: 167,
   NAME: "Second name",
   CODE: "CC"
  },
  {
   ID: 169,
   NAME: "Third name",
   CODE: "CCM"
  },
  {
   ID: 170,
   NAME: "Fourth name",
   CODE: "CR"
  },
];

var sortOrder =  ["CCM","CR","AD","CC"];

var sorted = array.sort((a, b) => sortOrder.indexOf(a.CODE) - sortOrder.indexOf(a.CODE));

console.log(sorted);




答案 4 :(得分:0)

如果你经常要做这样的事情,你可以写一个小实用程序来帮助:



const array = [{ ID: 168, NAME: "First name", CODE: "AD" }, { ID: 167, NAME: "Second name", CODE: "CC" }, { ID: 169, NAME: "Third name", CODE: "CCM" }, { ID: 170, NAME: "Fourth name", CODE: "CR" },{ ID: 166, NAME: "Fifth name", CODE: "CCM" }, { ID: 171, NAME: "Sixth name", CODE: "XXX" }, { ID: 172, NAME: "Seventh name", CODE: "CR" }]

const sortOn = (prop, list) => {
  const order = list.reduce((obj, key, idx) => Object.assign(obj, { [key]: idx + 1}), {});
  const getVal = item => order[item[prop]] || Infinity
  
  return (a, b) => getVal(a) - getVal(b)
}

array.sort(sortOn('CODE', ["CCM", "CR", "AD", "CC"]))
console.log(array)




order对象与Nina Scholz建议的非常相似。 idx + 1而非idx的原因是为了简化下一行。该行使用Infinity作为一种方法,在排序列表中对键值未定义或未定义的那些进行排序。如果您在开头想要它们,可以使用0-Infinity