How to sort array in postman?

By the way, I have two questions about my code - how to sort an array in Postman and if there is a better way to compare objects except mine. I use this block to compare properties to check equality of JSON objects body1 and body2 (I’m interested in equality of particular set of properties, f. e. body1 can have property “id” and body2 not, so it’s not about strict equality).

properties_list.forEach((property) => 
            (Array.isArray(body2[property])) ?
                (pm.expect((body1[property]).sort()).to.deep.equal((body2[property])).sort()) :
                (pm.expect(body1).to.have.deep.property(property, body2[property])));

But it seems that chai doesn’t support .sort()
Other ways to compare doesn’t work for me:

pm.expect(body1).to.have.deep.property(property, body2[property])); // or
pm.expect(body1[property]).to.deep.equal(body2[property]));

That ways doesn’t provide equality check in any order ([1, 2] will be not equal [2, 1]).

Hi @e.mikhailov, could you share an example of the response that you’re trying to compare/test?

@singhsivcan Yes, sure, but I can’t share request, so I will try to provide all code that needed.
Declaring of test function:

pm.environment.set("tests", function tests() {
    var tests = {},
    // technically it is not equality but check that body1 *contains* listed properties equal to body2 properties
    tests.equals = function equals(body1, body2, properties_list) {
        properties_list.forEach((property) => 
            pm.expect(body1).to.have.deep.property(property, body2[property])); //doesn't work for arrays
    };

    return tests;

} + '; tests();');

Calling of check:

var tests = eval(pm.environment.get("tests")),
    body1 = {
        "arr": [
            1,
            2,
            3
        ]
    },
    body2 = {
        "arr": [
            2,
            1,
            3
        ]
    };

tests.equals(body1, body2, ["arr"]);

Result:
deepequalserror

Why not keep it simple and make another function for arrayTest instead of reusing the one for object?

function checkArr(body1, body2) {
  let arr1 = body1.arr.sort(), //javascript has this in-built for arrays
    arr2 = body2.arr.sort();

  pm.expect(arr1).to.eql(arr2);
}
3 Likes

Thanks, that works! I’ve tried the same solution but without separate function to check and I seem to mistake somewhere. Your way works fine and I will check for mistakes in my similar solution.

Maybe, it was wrong to call body1[property].sort() or (body1[property]).sort() like I tried. Maybe, that was the matter.

hi sivcan
i want to get a date from an json response rows and sort it either descending or ascending?
Any idea if this is feasible in postman?

please ignore sivcan. I got the solution