在其属性值上对对象文字进行排序

时间:2018-04-03 19:12:00

标签: javascript arrays json alasql

下面是我的输入,我将循环遍历每个元素并将每个元素发送到另一个函数。

 distinctParameterList  =  [{
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 83,
        m05: 82,
        m08: 85,
        fymcl: 'FY18|PromotionsOut|AN-10000100:CL 2',
        m07: 84,
        m09: 86,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 95,
        m05: 94,
        m08: 97,
        fymcl: 'FY18|PromotionsOut|AN-10000110:CL 2',
        m07: 96,
        m09: 98,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 22,
        m05: 21,
        m08: 24,
        fymcl: 'FY17|PromotionsOut|AN-10000100:CL 2',
        m07: 23,
        m09: 25,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 42,
        m05: 41,
        m08: 44,
        fymcl: 'FY17|PromotionsOut|AN-10000110:CL 4',
        m07: 43,
        m09: 45,
        intersectionId: '54697113|India|520|N'
    }]

我还在下面计算一个值“calcCareerId”:

let calcCareerId = fymclData.split("-")[1].split(":")[0];

现在我想根据fymcl属性中的“calcCareerId”值对这个结构进行排序,这样我就可以先获得所有“10000100”值,然后再获得“10000110”。

1 个答案:

答案 0 :(得分:0)

定义功能:



let calcCareerId = fymclData => fymclData.split("-")[1].split(":")[0];




您可以使用lodash's sortBy函数按字典顺序升序排序。如果您想降序,只需在结果上调用.reverse即可。



const result = _.sortBy(distinctParameterList, ({fymcl}) => calcCareerId(fymcl));




或使用原生sort



const result = distinctParameterList.sort((a, b) => {
  const valueA = calcCareerId(a.fymcl);
  const valueB = calcCareerId(b.fymcl);
  return (valueA === valueB) ? 0 : (valueA < valueB ? 1 : -1)
})
&#13;
&#13;
&#13;

请注意,本机sort会改变数组并且不稳定。