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.

7
  • 3
    post your forEach code. Commented Jul 28, 2014 at 14:30
  • documentcloud.github.io/underscore/#union Commented Jul 28, 2014 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 Commented Jul 28, 2014 at 14:31
  • I don't know how to mark as duplicate, but this post: stackoverflow.com/questions/13319150/… goes over the same thing. Oh, and for the record, the library you want is underscore. (underscorejs.org). It's pretty magical. Commented Jul 28, 2014 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 Commented Jul 28, 2014 at 14:38

2 Answers 2

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
        });
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure this is working @Johny? What am I missing? jsfiddle.net/4JUqT
I updated the solution. Didn't realize at first that these things are objects inside array positions.
Yeah, thanks what makes me think why the OP set is as valid response without saying anything
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]);      
}

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.