1. /**
  2. * Removes duplicate datasets from an array.
  3. *
  4. * @param {Array<object>} datasets An array of datasets (objects).
  5. * @param {string} key The key to use for checking duplicates. Defaults to 'id'.
  6. * @returns {Array<object>} A new array with duplicates removed. Returns an empty array if input is invalid.
  7. */
  8. function removeDuplicateDatasets(datasets, key = 'id') {
  9. if (!Array.isArray(datasets)) {
  10. console.error("Invalid input: datasets must be an array.");
  11. return [];
  12. }
  13. if (datasets.length === 0) {
  14. return []; // Return empty array if input is empty.
  15. }
  16. if (typeof key !== 'string' || key.trim() === '') {
  17. console.error("Invalid input: key must be a non-empty string.");
  18. return [];
  19. }
  20. const seen = new Set();
  21. const result = [];
  22. for (const dataset of datasets) {
  23. if (typeof dataset !== 'object' || dataset === null) {
  24. console.warn("Skipping invalid dataset:", dataset);
  25. continue;
  26. }
  27. if (dataset.hasOwnProperty(key)) {
  28. const keyValue = dataset[key];
  29. if (!seen.has(keyValue)) {
  30. seen.add(keyValue);
  31. result.push(dataset);
  32. }
  33. } else {
  34. console.warn(`Dataset missing key '${key}':`, dataset);
  35. }
  36. }
  37. return result;
  38. }

Add your comment