Remove items from one array if not in the second array

前端 未结 5 1997
清酒与你
清酒与你 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:34

    Do it like this:

    //the array which will loose some items
    var ar1 = ["a", "b", "c"];
    //the array which is the template
    var ar2 = ["d", "a", "b"];
    
    var tmpar = [];
    
    for(var i = 0; i < ar1.length; i++){
      if(ar2.indexOf(ar1[i]) !== -1){
        tmpar.push(ar1[i]);
      }
    }
    
    ar1 = tmpar;
    
    alert(ar1);

    We create a temporary array to store the valid values.

    We make sure that the index of the value from the first array is not "-1". If it's "-1" the index is not found and therefore the value is not valid! We store everything which is not "-1" (so we store every valid value).

提交回复
热议问题