Source: filtering/index.js

  1. /**
  2. * @module filtering
  3. */
  4. /**
  5. * Filter and sort ascending the input records
  6. * based on their titles.
  7. * @param {Array} records
  8. * @return {Array} sorted & filtered records
  9. */
  10. const filterAndSortByTitle = (records) => {
  11. const uniqueObjects = new Map();
  12. records.forEach(e => {
  13. uniqueObjects.set(e.title, e);
  14. });
  15. return [...uniqueObjects.values()].sort((a, b) => a.title.localeCompare(b.title));
  16. };
  17. /**
  18. * Group all input records based on parent variable name.
  19. * Returns an object where the object parameters are the
  20. * different values of the parent variable name.
  21. * @param {Array} records which have a parent ID
  22. * @param {String} parentIdName variable name for parent ID
  23. * @return {Object} grouped records
  24. */
  25. const groupByParent = (records, parentIdName) => {
  26. const recordsMap = new Map();
  27. const sortedObject = {};
  28. records.forEach(e => {
  29. const parentId = e[parentIdName];
  30. let record = [];
  31. if (!recordsMap.has(parentId)) {
  32. record = [];
  33. } else {
  34. record = recordsMap.get(parentId);
  35. }
  36. record.push(e);
  37. recordsMap.set(parentId, record);
  38. });
  39. for (const [key, value] of recordsMap) {
  40. sortedObject[key] = value;
  41. }
  42. return sortedObject;
  43. };
  44. module.exports = {
  45. filterAndSortByTitle,
  46. groupByParent,
  47. };