2

Compare two array of objects to find distinct values by key number

Suppose the old object consists of

oldChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }]

and new object consists of

newChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }, {"number": 3, "text": "xyz" }]

So need to get:

[{"number": 3, "text": "xyz" }]

Note: 1. Values populate in the newChoices array on the keypress event of the textbox. 2. newChoices can get value at the start as well.

Attempt 1:

var uniqueTemp = [];
$.each(oldChoices, function(x, e1){
   $.each(newChoices, function(y, e2){
      if(e1.number != e2.number){
         uniqueTemp.push(e2);
      }
   });
})

Attempt 2:

var uniqueTemp = [];
oldChoices.filter(function(x){
   if(newChoices.indexOf(x.number) === -1){
    uniqueTemp.push(x);
    return true;
   }else{
    return false;
   }
});

Expected:

[{"number": 3, "text": "xyz" }]
N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32

4 Answers4

3

Your second attempt is close, just change to:

newChoices.filter((x) => {
   return (!oldChoices.find((choice) => choice.number === x.number));
});
volcanic
  • 312
  • 1
  • 6
3

You could take a Set and filter the new array.

var oldChoices = [{ number: 1, text: "abc" }, { number: 2, text: "pqr" }],
    newChoices = [{ number: 1, text: "abc" }, { number: 2, text: "pqr" }, { number: 3, text: "xyz" }],
    old = new Set(oldChoices.map(({ number }) => number)),
    result = newChoices.filter(({ number }) => !old.has(number));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Here is your solution . Simple use the flag for it .
in arr you will have a unique object as expected .

var oldChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }]
var newChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }, {"number": 3, "text": "xyz" }];
var arr = []
var flag = 0;
newChoices.forEach(function(newChoice){
    oldChoices.forEach(function(oldChoice){
        if(oldChoice.number == newChoice.number){
            flag = 1;
        }
    });
    if(flag != 1){
        arr.push(newChoice);
    }
    flag = 0;
});

console.log(arr);
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
0

This is a generic function that calculates the difference of two arrays:

let arrayDifference = (v1, v2, cmp = null) => 
  [...v1.filter(o1 => !v2.some(o2 => cmp ? cmp(o1, o2) : o1 === o2)),  
   ...v2.filter(o1 => !v1.some(o2 => cmp ? cmp(o1, o2) : o1 === o2))]

Than you can invoke it with the right comparison function:

arrayDifference(
  oldChoices,
  newChoices,
  (o1, o2) => o1.number === o2.number
)

This function finds the unique objects that occurs both in oldChoices and in newChoices.

Giancarlo
  • 9
  • 2