function findUniqueElements(arr) {
if (!Array.isArray(arr)) {
return "Invalid input: Input must be an array.";
}
const uniqueElements = [];
const elementCounts = {}; // Use an object to store counts efficiently
for (const element of arr) {
if (elementCounts[element]) {
elementCounts[element]++;
} else {
elementCounts[element] = 1;
uniqueElements.push(element);
}
}
return {
uniqueElements: uniqueElements,
elementCounts: elementCounts,
totalCount: uniqueElements.length
};
}
// Example usage:
const myArray = [1, 2, 2, 3, 4, 4, 5, 5, 5];
const result = findUniqueElements(myArray);
console.log(result);
// Expected output:
// {
// uniqueElements: [ 1, 2, 3, 4, 5 ],
// elementCounts: { '1': 1, '2': 2, '3': 1, '4': 2, '5': 3 },
// totalCount: 5
// }
const myArray2 = [true, "hello", true, 5, "hello", "world", 5, 5];
const result2 = findUniqueElements(myArray2);
console.log(result2);
// Expected output:
// {
// uniqueElements: [ true, 'hello', 5, 'world' ],
// elementCounts: { true: 2, 'hello': 2, '5': 3, 'world': 1 },
// totalCount: 4
// }
// Test with invalid input
const invalidInput = "not an array";
const invalidResult = findUniqueElements(invalidInput);
console.log(invalidResult); // Output: Invalid input: Input must be an array.
This improved version offers a few key advantages:
- Handles various data types: Correctly counts unique elements even if the array contains mixed data types (numbers, strings, booleans, etc.).
- Clearer Return Value: Returns an object containing the unique elements, the counts of each unique element, and the total count of unique elements. This makes the result much more usable.
- Efficient Counting: Uses a JavaScript object (
elementCounts
) to store the counts of each element. This provides efficient lookups (checking if an element has already been seen). - Input Validation: Includes a check to ensure the input is an array and returns an appropriate message if it's not. This makes the function more robust.
This function provides a comprehensive solution for finding and counting unique elements in a JavaScript array. It's efficient, handles different data types, and provides a user-friendly return value.