Reputation: 13
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:
uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3]) == [1,2,3]
I tried solving this problem using a filter function on the given parameter. Here is my attempt:
var uniqueInOrder = function (iterable) {
return iterable.filter(function(current, index, array){
if (index === 0){
return true;
}
else if (current[current.length - 1] === array[index]){
return false;
}
else {
return true;
}
});
};
The issue is that I get this error and I don't understand why it doesn't detect filter as a function.
Here is the parameter I give it:
uniqueInOrder("AAAABBBCCDAABBB");
Here is the error:
const newArray = iterable.filter(function (current, index, array) {
^
TypeError: iterable.filter is not a function
at uniqueInOrder (c:\Users\Anthony\source\repos\Web Dev\Unique in Order\script.js:2:29)
at Object.<anonymous> (c:\Users\Anthony\source\repos\Web Dev\Unique in Order\script.js:15:1)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
Upvotes: 1
Views: 197
Reputation: 2201
Strings are not arrays (opposed to some other languages), so they don't provide a filter
method:
Either convert the given iterable
parameter to an array with iterable = Array.from(iterable)
(Array.from is not natively supported by IE) or explicitly split strings with if (typeof iterable === 'string') { iterable = iterable.split(''); }
Upvotes: 0
Reputation: 44125
Strings don't have filter
- plus, it's a lot simpler to make a Set
then convert to an array:
var uniqueInOrder = iterable => [...new Set(iterable)];
Or to keep with your idea (ignoring your algorithm and simply fixing the error), do a simple ES6 spread:
return [...iterable].filter(...);
Or if it's an old environment:
return (typeof iterable == "string" ? iterable.split("") : iterable).filter(...);
Upvotes: 1