【问题标题】:Math Set Functions on Associative array in JavascriptJavascript中关联数组的数学集函数
【发布时间】:2012-08-25 18:12:01
【问题描述】:

如何在Javascript中获取两个关联数组的差异。? 示例:

var arr1[0] = { name : 'test1' , type : 'test2' };
var arr1[1] = { name : 'test2' , type : 'test3' };
var arr2[0] = { name : 'test1' , type : 'test2' };
var arr2[1] = { name : 'test3' , type : 'test4' };

我需要这样的输出

if Intersection() :
arr3[0] = { name : 'test1' , type : 'test2' }
if difference arr1-arr2 :
arr4[0] = { name : 'test2' , type : 'test3' };
if difference arr2-arr1 :
arr5[0] = { name : 'test3' , type : 'test4' };

我在搜索中没有找到任何与关联数组有关的内容。

【问题讨论】:

    标签: javascript arrays associative-array intersection


    【解决方案1】:
    function equals(a, b){
           return (a.name === b.name && a.type === b.type);            
        }
    
        function has(arr, obj){
            var len = arr.length;
    
            for(var i = 0; i < arr.length; i++){
                if(equals(arr[i], obj)) return true;                               
            }
    
            return false;        
        }    
    
        function clone(obj){
            return {
                name: obj.name,
                type: obj.type
            };        
        }
    
    
        function intersect(a, b){
            var common = [];    
            if(!a.length || !b.length) return common;
    
            var aLen = a.length;
            for(var i = 0; i < aLen; i++){
                if(has(b, a[i])){
                    common.push(clone(a[i]));   
                }            
            }
    
            return common;              
        }
    
    
    
    
        function subtract(a, b){
           var result = [];    
            if(!a.length || !b.length) return result;
    
            var common = intersect(a, b);
            var aLen = a.length;
    
            for(var i = 0; i < aLen; i++){
                if(!has(common, a[i])){
                    result.push(clone(a[i]));   
                }               
            }
    
            return result;
        }
    
        var arr1 = [{ name : 'test1' , type : 'test2' },{ name : 'test2' , type : 'test3' }];
    
        var arr2 = [{ name : 'test1' , type : 'test2' }, { name : 'test3' , type : 'test4' }];
    
        console.log(intersect(arr1, arr2));
        console.log(subtract(arr1, arr2));
        console.log(subtract(arr2, arr1)); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 2010-10-09
      • 2011-07-22
      • 1970-01-01
      相关资源
      最近更新 更多