array_diff in JavaScript

To get elements from the array that are not present in another array.

var a = [2, 4, 8, 16, 32],
    b = [2, 4, 32, 64, 128, 256];

// Define custom method on Array prototype
// Pass the array as parameter
Array.prototype.diff = function (arr) {

    // Merge the arrays
    var mergedArr = this.concat(arr);

    // Get the elements which are unique in the array
    // Return the diff array
    return mergedArr.filter(function (e) {
        // Check if the element is appearing only once
        return mergedArr.indexOf(e) === mergedArr.lastIndexOf(e);
    });
};

// How to call?
var diff = a.diff(b);

console.log(diff);
document.write('<pre>' + JSON.stringify(diff, 0, 4) + '</pre>');

[
    8,
    16,
    64,
    128,
    256
]

Shorter version:

var diff = array1.concat(array2).filter(function (e, i, array) {
    // Check if the element is appearing only once
    return array.indexOf(e) === array.lastIndexOf(e);
});
Mudasir Abbas Turi

Hi, this is Mudasir Abbas Turi. I am a Full-stack PHP and JavaScript developer with extensive experience in building and maintaining web applications. Skilled in both front-end and back-end development, with a strong background in PHP and JavaScript. Proficient in modern web development frameworks such as Laravel and ReactJS. Proven ability to develop and implement highly interactive user interfaces, and to integrate with various APIs and databases. Strong problem-solving skills and ability to work independently and as part of a team. Passionate about staying up-to-date with the latest technologies and industry trends.

Post a Comment

Previous Post Next Post