算法得到两个阵列之间的变化 [英] Algorithm to get changes between two arrays

查看:112
本文介绍了算法得到两个阵列之间的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一种算法,能够(有效)取一个旧阵列和新阵列,并给我回了两者之间的变化(哪些项目增加,其中删除)。这恰好需要在JavaScript的(在浏览器中运行),但该算法的比语言更重要。

I needed to create an algorithm which will (efficiently) take an old array and a new array and give me back the changes between the two (which items added, which removed). It happens to need to be in JavaScript (to run in the browser) but the algorithm's more important than the language.

这就是我想出了: http://jsbin.com/osewu3/13 。任何人都可以看到的任何问题/建议任何改善?

This is what I came up with: http://jsbin.com/osewu3/13. Can anyone see any problems with that/suggest any improvements?

谢谢!

code清单:

function diff(o, n) {
  // deal with empty lists
  if (o == undefined) o = [];
  if (n == undefined) n = [];

  // sort both arrays (or this won't work)
  o.sort(); n.sort();

  // don't compare if either list is empty
  if (o.length == 0 || n.length == 0) return {added: n, removed: o};

  // declare temporary variables
  var op = 0; var np = 0;
  var a = []; var r = [];

  // compare arrays and add to add or remove lists
  while (op < o.length && np < n.length) {
      if (o[op] < n[np]) {
          // push to diff?
          r.push(o[op]);
          op++;
      }
      else if (o[op] > n[np]) {
          // push to diff?
          a.push(n[np]);
          np++;
      }
      else {
          op++;np++;
      }
  }

  // add remaining items
  if( np < n.length )
    a = a.concat(n.slice(np, n.length));
  if( op < o.length )
    r = r.concat(o.slice(op, o.length));

  return {added: a, removed: r}; 
}

(我还张贴了这个作为一个潜在的解决方案,另外一个SO的问题,在这里:<一href="http://stackoverflow.com/questions/1187518/javascript-array-difference/3476612#3476612">http://stackoverflow.com/questions/1187518/javascript-array-difference/3476612#3476612)

推荐答案

下面的页面有一个功能,删除一个阵列从另一个可以用来给你2的值。 从具有RemoveArrayItems JavaScript数组删除项目( )

The following page has a function that removes one array from another and can be used to give you the 2 values. Remove items from a JavaScript Array with RemoveArrayItems()

var newItemsAdded=RemoveArrayItems(oldArray,newArray);
var ItemsRemoved =RemoveArrayItems(newArray,oldArray);

这篇关于算法得到两个阵列之间的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆