Middle+
// The findUnique method is applied to the array, which returns a new array of unique elements, // i.e., those that appear only once in the original array, in the same order. // Implement the findUnique method so that it works like a regular array method [10, 5, 10, 1, 6, 6, 7, 9, 9, 10].findUnique(); // [5, 1, 7]
sobes.tech AI
Answer from AI
To add a findUnique method to an array that returns a new array of elements that occur exactly once in the original array, you can extend the array prototype as follows:
Array.prototype.findUnique = function() {
const counts = this.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
return this.filter(item => counts[item] === 1);
};
// Example usage:
const arr = [10, 5, 10, 1, 6, 6, 7, 9, 9, 10];
console.log(arr.findUnique()); // [5, 1, 7]
Explanation:
- First, create an object
countswhere keys are array elements and values are their occurrence counts. - Then filter the original array, keeping only those elements whose occurrence count is 1.
This method works like a regular array method and preserves the order of elements.