Skip to main content
Known Participant
July 31, 2022
Question

Sorting a list by birthday

  • July 31, 2022
  • 1 reply
  • 689 views

Hi, 

I am using Acrobat Pro DC and have created a form where you can enter 

First Name (Name1), Last Name (NName1) and Birthday (B1)

To sort the list alphabetically (without birthday) I am using following code...

// Get the field values, as strings

var s1 = getField("Name1").valueAsString;

var l1 = getField("NName1").valueAsString;

var s2 = getField("Name2").valueAsString;

var l2 = getField("NName2").valueAsString;

var s3 = getField("Name3").valueAsString;

var l3 = getField("NName3").valueAsString;

// Combine values, separated by a space

event.target.value = s1 + " " + l1 + ",\n" + s2 + " " + l2 + ",\n" + s3 + " " + l3;

if(event.value!=""){ 

var names = event.value.split("\r");

names = names.sort(function(a,b){if(a<b)return -1; if(a>b)return 1; return0});

event.value=names.join("\r");

 

However, I would now like to incorparate the birthday and ideally put the list in order of the birthday from youngest to oldest or oldest to youngest. 

What would I need to change in my java script? I would very much appreciate any help. 

Thank you in advance.

1 reply

try67
Community Expert
Community Expert
July 31, 2022

There are several ways to do this, but all would include adjusting the sort method to examine the DOB value, instead of the name. You can do it by combining the values to a single string and then split it in the sort method to extract the DOB, convert it to a Date object (using util.scand) and then compare them (using their getTime method), or you could use an array of literal objects with a name property and a DOB property, and then sort based on the latter. Then you recombine the array into a single string and apply it as the field's new value.

Known Participant
August 2, 2022

Thank you very much try67. Unfortunately I am quite new to java script and find it difficult to write it from scratch. I managed to write the above with some help from this lovely community. Would it be difficult to give me script example which I can then adapt to my fields?

 

try67
Community Expert
Community Expert
August 2, 2022

Here you go:

 

var data = [];

var s1 = getField("Name1").valueAsString;
var l1 = getField("NName1").valueAsString;
var b1 = getField("B1").valueAsString;
data.push({name: s1 + " " + l1, dob: b1}); // repeat for other fields

data.sort(sortByDOB);
var s = "";
for (var i=0; i<data.length; i++) s+=data[i].name + ", " + data[i].dob;
event.value = s;

function sortByDOB(a,b) {
	if (a.dob=="" && b.dob=="") return 0;
	if (a.dob=="" && b.dob!="") return 1;
	if (a.dob!="" && b.dob=="") return -1;
	var d1 = util.scand("mm/dd/yyyy", a.dob);
	var d2 = util.scand("mm/dd/yyyy", b.dob);
	return (d1.getTime()-d2.getTime());
}

 

The sortByDOB function will return the values in ascending order, by the way, with any empty values appearing at the end.