How to find the last object in the array

Hi!
In the below example I have API that will return list of sections, each section can contain some amount of Shows. First section title will be always “All Upcoming Shows”, and last section will always be “All Replay Shows”. There can be many different sections in-between them, with different names, but first and last sections should always have names “All Upcoming Shows” and “All Replay Shows”. So, I want to check that sections will have those names. For the first section it is pretty simple (

pm.test("First Category is 'All Upcoming Shows'", () => {
    const responseJson = pm.response.json();
    pm.expect(responseJson.items[0].sectionTitle).to.eql('All Upcoming Shows');
});

)
but how to indicate the last “sectionTitle” in the array if it can be different amount of sections all the time?
Please, help me with the solution.

{
    "items": [
        {
            "sectionTitle": "All Upcoming Shows",
            "shows": [
                {
                    "id": "12345"
                },
                {
                    "id": "12346"
                }
            ]
        },
		{
            "sectionTitle": "Title1",
            "shows": [
                {
                    "id": "12345"
                },
                {
                    "id": "12347"
                }
            ]
        },
		{
            "sectionTitle": "Title2",
            "shows": [
                {
                    "id": "12348"
                },
                {
                    "id": "12349"
                }
            ]
        },
		{
            "sectionTitle": "All Replay Shows",
            "shows": [
                {
                    "id": "12343"
                },
                {
                    "id": "12345"
                }
            ]
        }
		],
		"serverTimestamp": "2022-02-11T14:03:27.328Z"
		}

Hey @aieshachayka

You could use the _.first() and _.last() Lodash methods to find those in the response array.

const responseJson = pm.response.json();

pm.test("First Category is 'All Upcoming Shows'", () => {
    pm.expect(_.first(responseJson.items).sectionTitle).to.eql('All Upcoming Shows');
});

pm.test("Last Category is 'All Replay Shows'", () => {
    pm.expect(_.last(responseJson.items).sectionTitle).to.eql('All Replay Shows');
});

You could also use this to get the last item in the array:

pm.test("Last Category is 'All Replay Shows'", () => {
    pm.expect(responseJson.items[responseJson.items.length - 1].sectionTitle).to.eql('All Replay Shows');
});
6 Likes

thank you so much! works perfectly!

1 Like