0

Super simple example,

var beforeList = [{"name": "A"},{"name": "B"},{"name": "C"}]

var updateList = [{"name": "A"},{"name": "B"},{"name": "D"}]

I have to compare this two and if there is a missing data, i have to insert updatelist data to before List.

So the result I want is,

function someLogicHere(beforeList, updateList){
// some logic here
  return afterList(i.e [{"name": "A"},{"name": "B"},{"name": "C"},{"name": "D"}]  in here) 
}

Any good or awesome lib or plug-in is OK.

I made by myself with forEach but it really is bad.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
Canna
  • 3,614
  • 5
  • 28
  • 33
  • 3
    post your forEach code. – Mritunjay Jul 28 '14 at 14:30
  • http://documentcloud.github.io/underscore/#union – mitomed Jul 28 '14 at 14:30
  • 1
    There isn't a magic function that will do this for you, any solution you find will use a looping mechanism of some kind. Post your code and at least then we can help you improve it to something you would be satisfied with – Kevin B Jul 28 '14 at 14:31
  • I don't know how to mark as duplicate, but this post: http://stackoverflow.com/questions/13319150/union-of-array-of-objects-in-javascript goes over the same thing. Oh, and for the record, the library you want is underscore. (http://underscorejs.org). It's pretty magical. – bearoplane Jul 28 '14 at 14:35
  • If those objects ONLY contain the 'name' property, then you can just use underscore's pluck() to get the values (like: _(beforeList).pluck('name'); ) and then do a normal union() which will combine two lists, discarding duplicates – bearoplane Jul 28 '14 at 14:38
  • If the name attribute is unique I suggest you use an object for beforeList instead of an array, with the values of the name attribute as keys. That will save you having to search through an array for a name in order to update/add it. – James Jul 28 '14 at 15:04
  • AWESOME! underscore.js was the solution – Canna Jul 29 '14 at 01:38

2 Answers2

1

This should work.

var afterList = beforeList.slice(0); //Clones the array
var elementPresent;

for (var i = 0; i < updateList.length; i++) {
    elementPresent = false;

    for (var j = 0; j < updateList.length; j++) {
        if (updateList[i].name == afterList[j].name){
            elementPresent = true;
            break;
        }
    }

    if(!elementPresent){
        afterList.push({
            "name": updateList[i].name
        });
    }
}
Praind
  • 1,551
  • 1
  • 12
  • 25
0

One way:

var afterList = beforeList.slice(0);

// store all values for easy lookup
var lookup = {};
for (var i in beforeList)
    lookup[beforeList[i].name] = true;

// look for values not in updateList & add to beforeList
for (var i in updateList)
{
   if (!lookup[updateList[i].name])
      afterList.push(updateList[i]);      
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288