2

I have 2 json arrays as below and I will do an jQuery extend later. I would like to use jQuery and compare only all elements (a,b) from array1 against array2, to check whether the (a,b) exists in array2 and get the difference if exists.

I have tried the code as below but somehow I always got the unexpected console output as actual return below. I would appreciate for any advice.

var array1 = {a: "AT", b: "1000"};
var array2 = {c: 0, d: 100, a: "AT", b: "1002"};
console.log($(array1).not(array2).get());

Expected return:

[Object]
    0: Object
    b: "1000"
    __proto__: Object
    length: 1
    __proto__: Array[0]

Actual return:

[Object]
    0: Object
    a: "AT"
    b: "1000"
    __proto__: Object
    length: 1
    __proto__: Array[0]
1

1 Answer 1

3

I have refer to the link below and modify the given answer accordingly. The modified answer as below.

References: Compare two JSON arrays in JQuery or Javascript

Modified Answer:

var origArrayGroups = {c: 0, d: 100, a: "AT", b: "1002"};
var userArrayGroups = {a: "AT", b: "1000"};

var diff = {};
for (var prop in userArrayGroups) {
    console.log("Comparing element: " + prop);
    if(userArrayGroups[prop] != origArrayGroups[prop])
    {
        diff[prop] = origArrayGroups[prop];
        console.log("Result: " + userArrayGroups[prop] + "!=" + origArrayGroups[prop]);
    }
    else
    {console.log("Result: " + userArrayGroups[prop] + "==" + origArrayGroups[prop]);}

}

console.log(diff);

Actual Return:

Object {b: "1002"} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.