簡體   English   中英

如何從Javascript中的另一個數組中刪除數組的項目值集

[英]How to remove set of item values of array from another array in Javascript

var myFind_collections =[3,6,10,234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var pgRangeCollection = [234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];

for(v=0;v<=pgRangeCollection.length;v++){
    var pgMatch = pgRangeCollection[v];
    clear_pg_range(pgMatch);
    }

function clear_pg_range(pgMatch){
        //for(d=0;d<=myFind_collections.length-1;d++){
        for(d=0;d<=myFind_collections.length-1;d++){
            var docFound = parseInt(myFind_collections[d]);
            if(pgMatch===docFound){
                    myFind_collections.splice(myFind_collections[d],1);
                    alert(docFound + " was removed");
                }
            }
    }

alert(myFind_collections.length);

在上面的代碼中,我想刪除myFind_collections中等於pgRangeCollection的每個項目

我希望輸出為(3,6,10)但我得到的輸出為(248,249,250)

我不知道我在哪里犯錯,有人可以為此建議解決方案,

提前致謝

使用Array.filter

var myFind_collections =[3,6,10,234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var pgRangeCollection = [234,235,236,237,238,239,240,241,244,245,246,247,248,248,249,250];
var filtered = myFind_collections.filter(
                  function(a){return pgRangeCollection.indexOf(a) < 0}
               ); // => [ 3, 6, 10 ]

另請參見filter )和indexOf

答案應該使用KooiInc已經提出的.filter方法,但是由於IE是必需條件,因此我將使用Lodash或Underscore的差分方法:

_.difference(myFind_collections, pgRangeCollection) // [3,6,10]

只需通過CDN包含它即可: http ://cdnjs.com/libraries/lodash.js/

或者如果您已經有了jQuery:

 $(myFind_collections).not(pgRangeCollection).get() // [3,6,10]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM