Home > Back-end >  Sorting a JSON response data in Angular 8
Sorting a JSON response data in Angular 8

Time:04-05

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 1: some data

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

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

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

enter image description here

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.

CodePudding user response:

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);

CodePudding user response:

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]
  • Related