Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This (working) code is supposed to return a new array that consists of elements of both arrays that were not marked as duplicates (find duplicates in both arrays, remove such elements from both arrays and create an array from the leftovers, if any)

Is there a way to simplify this function?

function diff(arr1, arr2) {
    var arr1_filtered, arr2_filtered;

    arr1_filtered = arr1.filter(function (v) {
        return arr2.indexOf(v) == -1;
    });

    arr2_filtered = arr2.filter(function (v) {
        return arr1.indexOf(v) == -1;
    });

    return arr1_filtered.concat(arr2_filtered);
}
share|improve this question
    
Do you want to remove duplicate from resulting array too? – Tushar Nov 20 '15 at 8:50
    
yes, from both of them and then combine non-duplicates in one new array – Alex Bykov Nov 20 '15 at 8:56
up vote 2 down vote accepted

Create a function on Array.prototype that'll accept an array and filter the array by checking if the element is in the other array.

// Define a function on Array prototype
Array.prototype.arrayDiff = function (arr) {
    return this.filter(function (v) {
        return arr.indexOf(v) === -1;
    });
};

function diff(arr1, arr2) {
    // 1. Remove elements that are in arr2 from arr1
    //    i.e. arr1.arrayDiff(arr2)
    // 2. Remove elements that are in arr1 from arr2
    //    i.e. arr2.arrayDiff(arr1)
    // 3. Concat the result of both the arrays

    return arr1.arrayDiff(arr2).concat(arr2.arrayDiff(arr1));
}

// Define a function on Array prototype
Array.prototype.removeDuplicates = function(arr) {
  return this.filter(function(v) {
    return arr.indexOf(v) === -1;
  });
};

function diff(arr1, arr2) {
  return arr1.removeDuplicates(arr2).concat(arr2.removeDuplicates(arr1));
}

var arr = diff([1, 3, 4, 2, 5], [2, 45, 7, 42, 1, 6]);
document.write(JSON.stringify(arr));

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.