1. /**
  2. * Searches for content within date values in an array of objects.
  3. * Handles potential errors gracefully.
  4. *
  5. * @param {Array<Object>} data An array of objects, each containing a 'date' property.
  6. * @param {string} searchTerm The term to search for within the date values.
  7. * @returns {Array<Object>} A new array containing only the objects where the 'date' property contains the search term. Returns an empty array if input is invalid.
  8. */
  9. function searchDates(data, searchTerm) {
  10. if (!Array.isArray(data)) {
  11. console.error("Invalid input: data must be an array.");
  12. return [];
  13. }
  14. if (typeof searchTerm !== 'string') {
  15. console.error("Invalid input: searchTerm must be a string.");
  16. return [];
  17. }
  18. const results = [];
  19. for (const item of data) {
  20. if (typeof item !== 'object' || item === null) {
  21. console.warn("Skipping invalid item in data: ", item);
  22. continue;
  23. }
  24. if (item.date !== undefined && item.date !== null) {
  25. const dateString = String(item.date); // Convert date to string for searching
  26. if (dateString.includes(searchTerm)) {
  27. results.push(item);
  28. }
  29. } else {
  30. console.warn("Skipping item with missing or null date property:", item);
  31. }
  32. }
  33. return results;
  34. }

Add your comment