I have already solved “Sorted Union”, here is my code that passes the test (this is not the question yet ):
function uniteUnique(arr) {
// flatten arguments into a single array:
var i = 0;
var allArgs = [];
while ( arguments[i] ) {
allArgs = allArgs.concat( arguments[i] );
i++;
}
// filter unique values from allArgs: (this works)
var result = [];
for ( let x of allArgs ) {
if ( result.indexOf( x ) < 0 ) {
result.push( x );
}
}
return result;
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
Then I tried to rewrite the second ‘for’ loop with a .filter() instead. The logic is the same: for each element, check if it already exists in result and only add it if it does not. However, this code fails all tests, as filter() seems to pass through all values. The code:
function uniteUnique() {
// flatten arguments into a single array:
var i = 0;
var allArgs = [];
while ( arguments[i] ) {
allArgs = allArgs.concat( arguments[i] );
i++;
}
// filter unique values from allArgs: (This does NOT work)
var result = [];
result = allArgs.filter( function( x ) {
return result.indexOf( x ) < 0;
} );
return result;
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
My best guess is that the result array does not get updated while filter() is being executed, so indexOf() always returns -1, but is this right?
On edit: In fact, yes, this is how filter() seems to work, but I still can’t understand why! A simplest possible testcase:
<script>
var ar1 = [1,1]; // original array
var ar2 = []; // put only UNIQUE values here
ar2 = ar1.filter( function( x ) {
// return true only if x is not yet in ar2
return ( ar2.indexOf(x) < 0 );
})
console.log( ar2 );
</script>
Result is:
Array [ 1, 1 ]
so indeed, it seems that the resulting array cannot be read inside filter(). And I thought I understood filter()…