get difference between two arrays (including duplicates)

前端 未结 6 1839
终归单人心
终归单人心 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:41

    So, I'd:

    • Iterate the updated array, for each element check if it's present on original array, if it's present I remove it from original array (note: in the function below I copy the original object, so I don't affect it), else I push the element to the differences array. At the end, I return the differences array.

    This code is made to work on various browsers, thus I didn't use Array().indexOf and other newer methods of ECMAScript.

    function difference(updated, original) {
      var i, l;
      /* copy original array */
      var degradation = [];
      for (var i = 0, ol = original.length; i < ol; ++i)
        degradation[i] = original[i]
    
      var diff = [];
      for (i = 0, l = Math.max(updated.length, ol); i < l; ++i) {
        var upd = updated[i];
        var index;
        var b, found;
        /* find updated item in degradation */
        for (b = 0, found = false; b < ol; ++b) {
          if (degradation[b] === upd) {
            /* remove item from degradation */
            delete degradation[b];
            found = true;
            break;
          }
        }
        if (!found)
          diff.push(upd);
      }
      return diff;
    }
    

提交回复
热议问题