Search code examples
javascriptarraysjsonalasql

Sort an object literal on its attribute value


Below is my input, I would be looping through each of this element and sending each element to another function.

 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'
    }]

I am also calculating a value "calcCareerId " below :

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

Now i want to sort this structure on the basis of the "calcCareerId " value in fymcl attribute, so that i can get all the "10000100" values first and then "10000110".


Solution

  • Define the function:

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

    You can use lodash's sortBy function to sort in lexicographically ascending order. If you want descending order, just call .reverse on the result.

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

    or use the native 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)
    })

    Note that the native sort mutates the array and is not stable.