0

I have to sort the response JSON data as per the approved status. Response data is something like this; [0]: adjustmnetfileds: Array(2) [0]: some data [2]: some data

adjustments : Array(1) 0: approvedByName: 'Jack' taskName: 'Insurance' approvedStatus: 1

[2]: adjustmnetfileds: Array(2) [0]: some data [2]: some data

adjustments : Array(1) 0: approvedByName: 'Dan' taskName: 'Insurance-Test' approvedStatus: 2

JSON response is something like this (nested arrays) and I want to sort the response as per the "approvedStatus (either asc or desc). Snapshot attached for reference.

2 Answers2

0

Already answered here

You can use Array.sort()

Example :

function compare(a, b) {
  if (a.approvedStatus < b.approvedStatus) {
    return -1;
  }
  if (a.approvedStatus > b.approvedStatus) {
    return 1;
  }
  return 0;
}

let data: Array<{ field: any, approvedStatus: number }> = [{ field: {}, approvedStatus: 2 }, { field: {}, approvedStatus: 1 }]
data.sort(compare);
Meven
  • 1
0

You can use array sort() method by providing your custom compareFn.

const json = [
    {
        adjustmnetfileds: [
            'some data',
            'some data',
        ],
        adjustments: [
            {
                approvedByName: 'Jack',
                taskName: 'Insurance',
                approvedStatus: 1,
            }
        ]
    },
    {
        adjustmnetfileds: [
            'some data',
            'some data',
        ],
        adjustments: [
            {
                approvedByName: 'Dan',
                taskName: 'Insurance-Test',
                approvedStatus: 3,
            }
        ]
    },
    {
        adjustmnetfileds: [
            'some data',
            'some data',
        ],
        adjustments: [
            {
                approvedByName: 'Sam',
                taskName: 'Insurance-Test',
                approvedStatus: 2,
            }
        ]
    },
]

// This sorts into ASC order
json.sort((a, b) => a.adjustments[0].approvedStatus  - b.adjustments[0].approvedStatus);

// For sorting into DESC order
// json.sort((a, b) => b.adjustments[0].approvedStatus  - a.adjustments[0].approvedStatus);

console.log(json);

I hope, your JSON structure is correct.

Note that the array is sorted in place, and no copy is made.

If you want new array, then copy first and then apply sort on that.

const originalArr = [1, 2, 3]
const copied = [...originalArr]
rmalviya
  • 1,847
  • 12
  • 39
  • Hi, this code is not working. I have edited my question and added the snapshot with the correct JSON structure. Could you please open up the snapshot once again. The JSON contains 16 entries and then sub-entries – Abhinav Gupta Apr 05 '22 at 10:40
  • Please open the first attached snapshot and let me know how to sort according to approvedStatus field. – Abhinav Gupta Apr 05 '22 at 10:41