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
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>')
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>');
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>');
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;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.