Reputation: 71
In a regular function, I can use the same result array in each iteration:
_.unique = function(array) {
var result = [];
for (var i = 0; i < array.length; i++) {
if (result.indexOf(array[i]) < 0) {
result.push(array[i]);
}
}
return result;
};
How can I do the same (and keep pushing to my result array) when working with a recursive function?
_.unique = function(array) {
var result = [];
if (array.length === 0) {
return result;
} else {
if (result.indexOf(array[0]) < 0) {
result.push(array[0]);
}
return _.unique(array.slice(1));
}
return result;
};
Using this, I'm getting the wrong outputs. I can do this using a inside helper function, but I prefer not to.
Upvotes: 0
Views: 100
Reputation: 1094
You must, pass the result to another function so the called function knows if the item is unique. In the following code example, the array of unique items is passed with the name p_result
.
This is a working code example:
_.unique = function(array, p_result) {
if(!(Object.prototype.toString.call(p_result) == '[object Array]')) p_result = [];
var result = p_result;
if(array.length === 0) return result;
if(p_result.indexOf(array[0]) < 0) {
result.push(array[0]);
}
return _.unique(array.slice(1), result);
};
// e.g. _.unique([0, 1, 1, 2, 3, 7, 4]) gives [0, 1, 2, 3, 7, 4]
Example fiddle that uses the code above
Upvotes: 1