Using a build step in your pipeline.
To make it simple, I would simply put a simple bash in a sh step and get the number of builds for each jobs. Also please note that this will work only if you don't set a custom build number. :)
To get the list of jobs,
curl -s -g http://<jenkins-url>/api/json\?tree\=jobs\[name\] | jq -r '.jobs[].name' | awk -v ORS=, '{print $1}' | sed 's/,$/\n/'
To get the list of all builds associated pass the values from above command to the below for loop's jobname arguments.
for i in {jobname1,jobname2}; do count=$(curl -s http://<jenkins-url>/job/$i/api/json\?tree\=nextBuildNumber | jq .nextBuildNumber-1) && echo "\nJobName: $i \nNumber of builds:$count"; done;
EDIT-1
Copy the below script and call it in your Jenkinsfile. You can pass the number of jobs to keep as an argument. Change the build/job url as required within the job or just pass that as a parameter too.
#!/bin/bash
jobstokeep=$1
listofbuilds=$(curl -sg http://jenkins-url/job/jobName/api/json?tree=builds[number] | jq .[] | grep 'number' | sed 's/[^0-9]//g' | awk -v var=$jobstokeep 'NR>var' | awk -v RS='' -v OFS=',' '$1=$1')
echo $listofbuilds
for i in ${listofbuilds//,/ }; do curl -s $user:$pass -X POST http://jenkins-url/job/jobName/$i/doDelete && echo "Build $i is deleted"; done;
The above script will 1st print the number of jobs to delete as a comma separated value and then loop thru each job and delete them using curl command (Jenkins Rest API).