Sorted Union......What is wrong with my code

Sorted Union......What is wrong with my code
0

#1

Hi this is my code for sorted union

function uniteUnique(arr) {
var totalArray=[];
var unique=[];
for (i=0; i<arguments.length; i++){
totalArray.concat(arguments[i]);
}

totalArray.forEach(function(value){
if(unique.indexOf(value) === -1){
unique.push(value);
}
});
console.log(“unique =”+unique.length);
return unique;
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

thanks in advance


#2

Hi @Bala_Chandra

Your logic is fine, the problem is with this line:

totalArray.concat(arguments[i]);

The concat method actually returns a new array made up of the original array and the provided arguments: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

Because of this, your not modifying the totalArray and therefore it is empty when you call forEach on it.

Quick fix is to just assign the value from the concat method back to the totalArray

totalArray = totalArray.concat(arguments[i]);

#3

Oh i understood now thank you so much for the reply.

:slight_smile: