Remove items from one array if not in the second array

前端 未结 5 2060
清酒与你
清酒与你 2021-01-21 02:49

I state that I have tried for a long time before writing this post.

For an InDesign script, I\'m working with two array of ListItems. Now I\'m trying to remove the items

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-21 03:26

    You can make use of Array.prototype.filter and Array.prototype.concat to simply it:

    arr_A = ["a","b","d","f","g"]
    arr_B = ["a","g","k"]
    arr_C = ["h"]
    
    function getCommonItems(arrayA, arrayB, result) {
     result = result || [];
     result = result.concat(arrayA.filter(function(item) {
                return arrayB.indexOf(item) >= 0;    
              }));
     return result.sort();
    }
    
    alert(getCommonItems(arr_A, arr_B, arr_C).join(", "));
    alert(getCommonItems(arr_B, arr_A, arr_C).join(", "));

    For the first scenario:

    arr_A = ["a","b","d","f","g"]
    arr_B = ["a","c","f","h"]
    
    function getDifference(arrayA, arrayB, result) {
     return arrayB.filter(function(item) {
                return arrayA.indexOf(item) === -1;    
      }).sort();
    }
    
    alert(getDifference(arr_A, arr_B).join(", "));
    alert(getDifference(arr_B, arr_A).join(", "));

提交回复
热议问题