2

I am working on angular js and i am new to it. So I am stuck at a problem where I have to subtract two arrays containing objects.

For Eg.

var all = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
var old = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];

var newArray = [];

Now, I wanted to populate the 'newArray' variable with the objects that are not existing in 'old' list as below

newArray = [{id:'2',name:'B'},{id:'4',name:'D'}]

Is there anyway to achieve this in angular js? Thanks

4 Answers 4

1

You can do it using Array.prototype.forEach() and Array.prototype.some()

var all = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
var old = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];

var newArr = [];

all.forEach(function(e) {
    if(!old.some(s => s.id == e.id)) {
        newArr.push(e);
    }
});

document.write('<pre>' + JSON.stringify(newArr, 0, 2) + '</pre>');

Sign up to request clarification or add additional context in comments.

Comments

1

try this

var all = [{
  id: '1',
  name: 'A'
}, {
  id: '2',
  name: 'B'
}, {
  id: '3',
  name: 'C'
}, {
  id: '4',
  name: 'D'
}];
var old = [{
  id: '1',
  name: 'A',
  state: 'healthy'
}, {
  id: '3',
  name: 'C',
  state: 'healthy'
}];

var newlist = all.filter(function(a) {
  return old.filter(function(o) {
    return o.id == a.id
  }).length == 0
})
document.write('<pre>' + JSON.stringify(newlist, 0, 4) + '</pre>')

Comments

0

A proposal with linear complexity.

var all = [{ id: '1', name: 'A' }, { id: '2', name: 'B' }, { id: '3', name: 'C' }, { id: '4', name: 'D' }],
    old = [{ id: '1', name: 'A', state: 'healthy' }, { id: '3', name: 'C', state: 'healthy' }],
    result = function (array1, array2) {
        var o = {};
        array2.forEach(function (a) {
            o[a.id] = true;
        });
        return array1.filter(function (a) {
            return !o[a.id];
        });
    }(all, old);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Comments

0

This is not at all related to AngularJS. This is a javascript problem, and you can easily achieve this result by using the following code-

var new = all.filter(function(element) { 
    var res = $.grep(old, function(el) { 
        return el.id == element.id; 
    }); 
    if(res.length == 0) return element; 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.