Diff Two Arrays Feedback please?

Diff Two Arrays Feedback please?
0

#1

The following is my code. It works well but I don’t know why I feel like it is a crappy, elementary type solution. Should I just move on to the next challenge or seek to make it better? Any feedback would be great, thanks!

function diffArray(arr1, arr2) {
var smallArr;
var largeArr;
var index;

if (arr1.length > arr2.length) {
largeArr = arr1;
smallArr = arr2;
}
else if (arr1.length < arr2.length) {
largeArr = arr2;
smallArr = arr1;
}
else if (arr1.length === arr2.length) {
largeArr = arr2;
smallArr = arr1;
}
for (var i = 0; i < smallArr.length; i++) {
index = largeArr.indexOf(smallArr[i]);
if (index !== -1) {
largeArr.splice(index, 1);
}
if (index === -1) {
largeArr.push(smallArr[i]);
}
}

return largeArr;
}

diffArray([1, “calf”, 3, “piglet”], [1, “calf”, 3, 4]);


#3

Hi,

One small improvement you could already make is get rid of the last else if. Your two last conditions are arr1 < arr2 and arr1===arr2. You do the same thing inside them. So you can simplify it to:

if (arr1.length > arr2.length) {
largeArr = arr1;
smallArr = arr2;
}
else {
largeArr = arr2;
smallArr = arr1;
}

#4

Thank you for the advice! I really appreciate it! :smiley:


#5

Great idea! Thank you! :slight_smile:


#6

what do you think about this:

function diffArray(arr1, arr2) {
var newArr = [];
for(var i=0;i<arr2.length;i++){
arr1.push(arr2[i]);
}
for (var j=0;j<arr1.length;j++){
var help=0;
for(var k=0;k<arr1.length;k++){
if (arr1[j]===arr1[k]){
help+=1;
}
}
if (help<2){
newArr.push(arr1[j]);
}
}

return newArr;
}

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