DEV Community

Rajnish Katharotiya
Rajnish Katharotiya

Posted on

Function to get a difference of two arrays in javascript

Hello dev minds, Welcome again in a new episode of series called javascript useful snippets. In this series, I'm going to talk about some shortcodes and useful functions of javascript. These snippets can help you to make your development more efficient and faster. If you haven't read the previous episode please go first and check it from here otherwise stay tuned till the end to learn something new... 😊

Javascript Useful Snippets - difference()

We often need to get the difference between two arrays while development. difference() snippet can be used to get it done easily. This function will take two arrays as input and will return an array in output with unique records of both arrays. let's check the syntax out....

const difference = (first, second) => {
     const comaparingSet = new Set(second);
     return first.filter(x => !comaparingSet.has(x));

Here, as snippets show we have two input arguments named first and second in order. In function first, I've created a constant of a new set of an array of the second argument by using Set web API ( for your knowledge - new Set() will create just a unique clone of the array and all duplicate entries ).

In return, I'm filtering the first array with the condition if comparingSet includes my record. here if the current record will be including into comparingSet then it'll store into filter array otherwise will be skipped. (for your knowledge - new Set() prototype includes has() method to identify the existence of any record). Now let's look at the results...

const result = difference([1, 2, 3, 4, 5], [1, 2, 4]); // output:- [3,5]

As given the first argument, the second argument has fewer records so, as we see in the result it had returned the difference of both arrays in an array.

Thank you for watching/reading folks, if you found this informative and wanted to make me more content like this please support me on Patreon.

Now, Guys in the next episode I'm going to share a function to get a difference by a function of two arrays. so follow/subscribe to get notification...

Subscribe on youtube



Top comments (0)