This is all fine if you want to find a unique set of objects by looking up their ID in a one to many or many-to-many relationship. In my case, I want to list all unique working titles (sting values on an attribute) for all employees, so I can present them in a filter. In SQL I would have used SELECT DISTINCT on the “employee title” column.
Looping all employees and adding titles to a runtime data source while making sure no duplicates are added is extremely slow. What I ended up doing was to add a coded component with the following code:
function add_selected({ title }, index) {
return unique.actions.add_title({ title }) // This should return a Promise
.catch(console.error); // Keep the catch to handle potential errors
}
// Run add_selected for each unique title
function addAllTitles(uniqueResourceTypesWithTitles) {
// Create an array of promises by mapping over uniqueResourceTypesWithTitles
const promises = uniqueResourceTypesWithTitles.map((titleObj, index, array) => {
return add_selected(titleObj, index, array);
});
// Wait for all promises to resolve
Promise.all(promises).then(() => {
console.log('All uniqe titles added successfully.');
}).catch((error) => {
console.error('An error occurred', error);
});
}
function getUniqueResourceTypes(employees) {
const uniqueResourceTypes = new Map();
employees.forEach(employee => {
const { emloyee_title } = employee;
if (!uniqueResourceTypes.has(emloyee_title)) {
uniqueResourceTypes.set(emloyee_title, emloyee_title);
}
});
// Convert Map to an array of the values (emloyee_title in this case)
const result = Array.from(uniqueResourceTypes.values());
// Convert each value into a dictionary with a "title" key
const titledResourceTypes = result.map(type => ({ title: type }));
return titledResourceTypes;
}
// Get the unique resource types as dictionaries with "title" keys
const uniqueResourceTypesWithTitles = getUniqueResourceTypes(unique.data.employees.get());
addAllTitles(uniqueResourceTypesWithTitles);
What the code does is to read out all unique employee titles and populate a runtime object “Unique stings” with only one attribute called “Sting” I use the Unique String object class for to create “dynamic enumerations” that I use for filters in the UI.
Ugly but it works. Please suggest a better way if it exists.
I would love to see something like SELECT DISTINCT built in to Appfarm.
(You might ask why I don’t use enumerations for this kind of data but in my case these data is returned by API from another source, so I have no control on the string values used for employee titles)
Other related topics here on the forum : How to list unique values - #3 by Preben
Output only unique object classes in a many-to-many relationship data