we have a social media app, and each user has a number of people whom he's following, we represent it in an array of id's [userID1, userID2, userID2..userID900], and we have another array that represent all of the users who are online on the platform, [user1, user2...user1043], the goal is to retrieve all of the online users that a particular user is following, in other words we wanna take the common items in the two arrays, Now, I know that this can easily done with a nested loop, but I want a more optimised solution.
            Asked
            
        
        
            Active
            
        
            Viewed 51 times
        
    0
            
            
         
    
    
        dagoo
        
- 63
- 5
- 
                    2Does this answer your question? [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – gdrt Jul 12 '21 at 23:33
2 Answers
0
            
            
        *Edit: Probably the best performance you'll get is to convert the second array to either an object or a Map
const a1 = [1,2,3,4,5];
const a2 = [3,5,7,9];
const o2 = a2.reduce((a,o)=> { a[o] = true; return a; }, {});
const usingObj = a1.filter(x=> !o2[x]);
console.log(usingObj);
const m2 = new Map();
a2.forEach(x=> m2.set(x, true));
const usingMap = a1.filter(x=> !m2.has(x));
console.log(usingMap);--- Original answer ---
You could use a combination of filter and indexOf, like this:
const a1 = [1,2,3,4,5];
const a2 = [3,5,7,9];
const a3 = a1.filter(x=> a2.indexOf(x)<0);
console.log(a3);This will remove all items from a1 which also exist in a2.
*Edit: you could alternatively use includes instead of indexOf, as mentioned by @ColeHenderson. I tend to use indexOf because includes is relatively new. (Old dogs, new tricks) Code coverage isn't really much of a concern any more, includes has ~96% browser support
 
    
    
        David784
        
- 7,031
- 2
- 22
- 29
- 
                    1I would suggest using includes instead of indexOf, so line 3 becomes: const a3 = a1.filter(x=> a2.includes(x)); – Cole Henderson Jul 12 '21 at 23:33
- 
                    this is still a nested loop somehow, it's time complexity is o(n^2) which is not what i want – dagoo Jul 12 '21 at 23:37
- 
                    @dagoo edited to add a couple of options that should be much more performant – David784 Jul 12 '21 at 23:49
0
            
            
        Lodash js recommended
var presents = _.intersectionWith(array1, array2, _.isEqual);
var dif = _.differenceWith(array1, array2, _.isEqual);
_.differenceWith is only available since 4.0.0 lodash version
 
    
    
        Hamid Dezhkam
        
- 1
- 2