get difference between two arrays (including duplicates)

前端 未结 6 1832
终归单人心
终归单人心 2021-01-12 04:14

I see a lot of posts about how to get the difference and symmetric difference of an array in javascript, but I haven\'t found anything on how to find the difference, includi

6条回答
  •  死守一世寂寞
    2021-01-12 04:40

    You can do it the following steps (O(n)).

    Let a and b are two arrays

    Step 1. create map hash_map of array a value as key and number occurrences of this key as value.

    Step 2. push all the elements of array b in result which are not in a using hash_map.

    Step 3. push all the elements of array a in result which are not in b using hash_map.

    Here is complete code

    function diff(a, b) {
        //Step 1 starts here
    	var hash_map = a.reduce(function(map, key) {
    		map[key] = map[key] ? (map[key]+1) : 1;
    		return map;
    	}, {});
        //Step 1 ends here
        //Step 2 starts here
    	var result = b.filter(function(val) {
    		if(hash_map[val]) {
    			hash_map[val] = hash_map[val]-1;
    			return false;
    		}
    		return true;
    	});
        //Step 2 ends hers
        //Step 3 starts here
    	Object.keys(hash_map).forEach(function(key) {
    		while (hash_map[key]) {
    			result.push(key);
    			hash_map[key] = hash_map[key]-1;
    		}
    	});
        //Step 3 ends here
    	return result;
    }
    
    console.log(diff([1],[1,1,2]));
    console.log(diff([1,1,1],[1,1,1,1,1,2]));
    console.log(diff([1,1,3,4],[1,2,3]));
    console.log(diff([1,1,1,1,1,2], [1, 2, 1, 1, 3]));

提交回复
热议问题