Home  >  Article  >  Web Front-end  >  How to use JS to find the difference between arrays

How to use JS to find the difference between arrays

不言
不言Original
2018-07-14 17:29:503446browse

This article mainly introduces how to use JS to find the difference set of arrays. It has a certain reference value. Now I share it with you. Friends in need can refer to it

The first one: If not Considering the compatibility of IE8, Foreach can be used. This method finds the difference set of arr1 minus arr2.

arr1 = [1,2,3,4];
arr2 = [1,2,3];  
 subSet =  set2 =  subset = (!

The second is to use JQ's merge and The use of grep to find the difference set is compatible with mainstream browsers such as IE8 and chrome.

 alpha = [1, 2, 3, 4= [1,2,3=  $.merge($.grep(a,  $.inArray(i, b) == -1 $.inArray(i, a) == -1&& console.log( $.arrayIntersect(alpha, beta) );
//结果等于4

The third method using the ES6 set method is similar to the foreach method

var subSet = function(arr1, arr2) {    
var set1 = new Set(arr1);    
var set2 = new Set(arr2);    
var subset = [];    
for (let item of set1) {        
if (!set2.has(item)) {
            subset.push(item);
        }
    }    return subset;
};

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About js binary tree query traversal, insertion and flipping code

For the role of the $ symbol in jQuery analyze

The above is the detailed content of How to use JS to find the difference between arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn