最新数组和以前的数组值进行比较

时间:2018-04-13 04:44:05

标签: javascript arrays angularjs html5

我是javascript和angular的新手。现在这可能是一个重复的问题,但我在这方面面临问题,

所以,我有两个对象数组:

$scope.previous = [{name: 'A', Value: 'B'}, {name: 'ABC', value: 'PQR'}];

我有一个新的更新数组:

$scope.updated = [{name: 'A', value:'C'}, {name: 'K', value: 'S'}, {name: 'ABC', value: 'PQR'}]

现在更新只是在之前的一些操作之后变成这样。

否则,我想将此新版与之前的版本进行比较。

那么如果一个对象在之前没有出现并且已经更新,那么应该将它添加到diff数组中。再次如果一个对象在两个数组中是相同的,那么它不应该被添加到新数组中,并且如果一个对象存在于更新的数组中但不存在于前一个数组中,那么它不应该被添加到diff数组中。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)



var previous = [{name: 'A', Value: 'B'}, {name: 'ABC', value: 'PQR'}];
var updated = [{name: 'A', value:'C'}, {name: 'K', value: 'S'}, {name: 'ABC', value: 'PQR'}]

function comparer(otherArray){
  return function(current){
    return otherArray.filter(function(other){
      return other.value == current.value && other.display == current.display
    }).length == 0;
  }
}
var onlyInA = previous.filter(comparer(updated));
var onlyInB = updated.filter(comparer(previous));

console.log(onlyInA);
console.log(onlyInB);

difference = previous.filter(function(x) { return updated.indexOf(x) < 0 })

console.log(difference);
&#13;
&#13;
&#13;

&#13;
&#13;
var previous = [{name: 'A', Value: 'B'}, {name: 'ABC', value: 'PQR'}];
var updated = [{name: 'A', value:'C'}, {name: 'K', value: 'S'}, {name: 'ABC', value: 'PQR'}]

var presentInArray = _.intersectionWith(previous, updated, _.isEqual);
console.log(presentInArray) //present in array
var differenceInArray = _.differenceWith(previous, updated, _.isEqual);
console.log(differenceInArray);//difference in array
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

您可以使用lodash来区分两个对象数组

希望这有帮助!

答案 1 :(得分:0)

这很简单,无需添加额外的库解决方案。我认为名称在每个对象中都是唯一的,在你的情况下可能会有所不同。

&#13;
&#13;
 

      const prev = [{name: 'A', value: 'C'}, {name: 'ABC', value: 'PQR'},{name: 'sss', value: 'sss'} ];
    const latest = [{name: 'AX', value:'CX'}, {name: 'K', value: 'S'}, {name: 'ABC', value: 'PQR'}];
      const whatDoesNotInclude = [];
const inPrevNotInLatest = [];
    
    const searchByname = (nameKey, myArray) => {
        for (var i=0; i < myArray.length; i++) {
            if (myArray[i].name === nameKey) {
                return myArray[i];
            }
        }
    }
    
    latest.forEach(l =>{
      if (searchByname(l.name, prev)) {   
      }else {
        whatDoesNotInclude.push(l);
      }
    });

 prev.forEach(l =>{
      if (searchByname(l.name, latest)) {   
      }else {
        inPrevNotInLatest.push(l);
      }
    });
    
    console.log(whatDoesNotInclude);
console.log(inPrevNotInLatest);
&#13;
&#13;
&#13;