Middle+
// findUnique meetod rakendub massiivile ning tagastab uue massiivi unikalseid elemente, // see tähendab, neid, mis esinevad algselt massiivis ainult üks kord, samas järjekorras. // On vaja rakendada findUnique meetod nii, et see töötaks nagu tavaline massiivi meetod [10, 5, 10, 1, 6, 6, 7, 9, 9, 10].findUnique(); // [5, 1, 7]
sobes.tech AI
Vastus AI-lt
To add the findUnique method to an array, which returns a new array with elements that appear 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);
};
// Usage example:
const arr = [10, 5, 10, 1, 6, 6, 7, 9, 9, 10];
console.log(arr.findUnique()); // [5, 1, 7]
Explanation:
- First, we create an object
counts, where the keys are the array elements and the values are the number of their occurrences. - Then, we filter the original array, keeping only those elements whose occurrence count is 1.
This way, the method works like a normal array method and preserves the order of elements.