cobbmic
September 13, 2018, 4:24pm
1
Ok. I don’t know why this isn’t working. Can someone enlighten me?
function uniteUnique(arr) {
arr = Array.prototype.slice.call(arguments);
arr = [].concat.apply(arr);
arr = arr.filter( function (item, pos) {
return arr.indexOf(item) == pos;
});
return arr;
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
cobbmic
September 13, 2018, 4:43pm
3
I was expecting the first line to create the array that you wrote.
I am expecting the second line to flatten out the array (remove the nested array).
I am expecting the filter function to remove any duplicates but leave the first occurrence.
cobbmic
September 13, 2018, 4:47pm
5
[ 1, 3, 2,5, 2, 1, 4 , 2, 1 ]
cobbmic
September 13, 2018, 5:13pm
7
Oh! It should be the following:
arr = [].concat.apply([], arr);
Right?
Yep. You can break it down conceptually like this:
['placeholder'].concat.apply(['original', 'array'], [['arrays'], ['to'], ['concatenate']]);
// => ["original", "array", "arrays", "to", "concatenate"]
Note that the placeholder array is discarded (regardless of whether or not it contains any data) — the only reason we need it is as shorthand to get that concat
method from the array prototype:
Array.prototype.concat === [].concat;
// => true
cobbmic
September 14, 2018, 1:24pm
10
Wow! thanks to both of you. Very helpful.