/**
* Searches for content within date values in an array of objects.
* Handles potential errors gracefully.
*
* @param {Array<Object>} data An array of objects, each containing a 'date' property.
* @param {string} searchTerm The term to search for within the date values.
* @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.
*/
function searchDates(data, searchTerm) {
if (!Array.isArray(data)) {
console.error("Invalid input: data must be an array.");
return [];
}
if (typeof searchTerm !== 'string') {
console.error("Invalid input: searchTerm must be a string.");
return [];
}
const results = [];
for (const item of data) {
if (typeof item !== 'object' || item === null) {
console.warn("Skipping invalid item in data: ", item);
continue;
}
if (item.date !== undefined && item.date !== null) {
const dateString = String(item.date); // Convert date to string for searching
if (dateString.includes(searchTerm)) {
results.push(item);
}
} else {
console.warn("Skipping item with missing or null date property:", item);
}
}
return results;
}
Add your comment