代码之家  ›  专栏  ›  技术社区  ›  helle

替换JavaScript中两个数组中出现的项

  •  0
  • helle  · 技术社区  · 15 年前

    我有两个数组,希望从一个数组中删除另一个数组中存在的所有元素。

    • 这可以用本地JS完成吗?
    • 有jquery函数吗?
    • 最佳实践是什么 越快越好)

    另外:也可以用其他语言发布代码,也许我可以把它移植到javascript上。

    更新,接受回答后帮助JS伙计;-)

    // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };
    // Array Contains - By Helmuth Lammer (TU Vienna)
    Array.prototype.contains = function(key){
    
        for(var i = 0; i<this.length; i++){
            if(this[i]  == key) return i;
        }
    
        return false;
    }
    

    (也有一个名为contains的本地JS方法,但它应该可以工作)

    4 回复  |  直到 12 年前
        1
  •  1
  •   corsiKa    15 年前

    给定两个集合a和b,从b中删除a中存在的所有元素。将转换为数组格式,并将javascript作为练习留给读者。已排序数组存在优化。

    for(element e : b) {
        if(a.contains(e)) {
             b.remove(e);
        }
    }
    
        2
  •  1
  •   lawnsea    15 年前
    var foo = [1, 2, 3, 4, 5];
    
    function removeAll(a, b) {
        var i = 0,
            j;
    
        while (i < b.length) {
            for (j = 0; j < a.length; j++) {
                if (a[j] === b[i]) {
                    b.splice(i, 1);
                    i--;
                    break;
                }
            }
            i++;
        }
    }
    
    removeAll([2, 4], foo);
    // foo === [1, 3, 5]
    
        3
  •  0
  •   gblazex    15 年前

    [ See it in action ]

    // two arrays
    var arr1 = [1,2,3,4,5];
    var arr2 = [4,5,6,7,8];
    
    // returns the element's index in an array
    // or -1 if there isn't such an element
    function indexOf( arr, el ) {
      for ( var i = arr.length; i--; ) {
        if ( arr[i] === el ) return i;
      }
      return -1;
    }
    
    // go through array1 and remove all
    // elements which is also in array2
    ​for ( var i = arr1.length; i--; )​ {
      if ( indexOf( arr2, arr1[i] ) !== -1 ) {
        arr1.splice(i, 1);
      }
    }
    
    // result should be: arr1 = [1,2,3] 
    alert( arr1 );
    ​
    
        4
  •  0
  •   Cesar Canassa    15 年前

    我曾经写过一个代码,在这个代码中,Ajax调用将返回一个包含必须从本地(客户端)数组中删除的元素列表的数组。

    我以这种方式结束了它的实现:

    // The filter method creates a new array with all elements that pass the
    // test implemented by the provided function.
    local_array = local_array.filter( function (element) {
        // Now I check if this element is present in the "delete" array. In order to do 
        // that I use the "some" method which runs a callback function for each of the
        // array elements and returns true or false.
        return !items_to_delete.some( function(item) {
            return item.pk === element.pk;
        });
    });
    

    编辑: 为了让它跨浏览器(我在这里说的是IE)。您必须定义一些和过滤函数。把这个放在你的代码里:

    if (!Array.prototype.some)
    {
      Array.prototype.some = function(fun /*, thisp*/)
      {
        var i = 0,
            len = this.length >>> 0;
    
        if (typeof fun != "function")
          throw new TypeError();
    
        var thisp = arguments[1];
        for (; i < len; i++)
        {
          if (i in this &&
              fun.call(thisp, this[i], i, this))
            return true;
        }
    
        return false;
      };
    }
    
    if (!Array.prototype.filter)
    {
      Array.prototype.filter = function(fun /*, thisp*/)
      {
        var len = this.length >>> 0;
        if (typeof fun != "function")
          throw new TypeError();
    
        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
          if (i in this)
          {
            var val = this[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, this))
              res.push(val);
          }
        }
    
        return res;
      };
    }