Home > Software design >  Compare two complex arrays in Jquery or Javascript
Compare two complex arrays in Jquery or Javascript

Time:01-25

I have two complex arrays and I want to compare them.

Array1 = [{INPUT_ID: 1, INPUT_VAL: "Test1", ACTIVE_FLAG: 1}, {INPUT_ID: 2, INPUT_VAL: "Test2", ACTIVE_FLAG: 1}, {INPUT_ID: 3, INPUT_VAL: "Test3", ACTIVE_FLAG: 1}, {INPUT_ID: 4, INPUT_VAL: "Test4", ACTIVE_FLAG: 1}]

Array2 = [{INPUT_ID: 1, INPUT_VAL: "Test1"}, {INPUT_ID: 2, INPUT_VAL: "Test2"}, {INPUT_ID:4, INPUT_VAL: "Test4"}, {INPUT_ID: 5, INPUT_VAL: "Test5"}]

I want to compare both of them and crete new Array or modify Array1

in Array1 I have INPUT_ID = 3 and in Array2 I don't have INPUT_ID = 3, So i want to mark ACTIVE_FLAG = "3" for INPUT_ID = 3 in Array1. I don't have INPUT_ID = 5 in Array2 but I have INPUT_ID = 5 in Array1 so I want to add this object to Array1 and mark ACTIVE_FLAG = "2".

my final Array should be like this.

Array1 = [{INPUT_ID: 1, INPUT_VAL: "Test1", ACTIVE_FLAG: 1}, {INPUT_ID: 2, INPUT_VAL: "Test2", ACTIVE_FLAG: 1}, {INPUT_ID: 3, INPUT_VAL: "Test3", ACTIVE_FLAG: 3}, {INPUT_ID: 4, INPUT_VAL: "Test4", ACTIVE_FLAG: 1}, {INPUT_ID: 5, INPUT_VAL: "Test3", ACTIVE_FLAG: 2}]

how can achive this using Jquery?

CodePudding user response:

Easier to read but inefficient (build the three groups, set the flag, concat and sort):

const inBoth = array1.filter(el1 => array2.some(el2 => el1.INPUT_ID === el2.INPUT_ID))
const minus = (a1, a2) => a1.filter(el1 => a2.every(el2 => el1.INPUT_ID !== el2.INPUT_ID))
const inFirst = minus(array1, array2)
const inSecond = minus(array2, array1)

inBoth.forEach(el => el.ACTIVE_FLAG = 1)
inFirst.forEach(el => el.ACTIVE_FLAG = 3)
inSecond.forEach(el => el.ACTIVE_FLAG = 5)

const res = [].concat(inBoth, inFirst, inSecond)
res.sort( (e1, e2) => e1.INPUT_ID - e2.INPUT_ID)

Ugly but efficient, input arrays must be sorted (go through both arrays at the same time and determine which element is next):

let ix1 = 0, ix2 = 0;
const res = []
while(ix1 < array1.length || ix2 < array2.length){
  const el1 = array1[ix1], el2 = array2[ix2]
  if(!el2 || (el1 && el1.INPUT_ID < el2.INPUT_ID)){
    // element is only in array1
    el1.ACTIVE_FLAG = 3
    res.push(el1)
    ix1  
    continue
  }
  const inBoth = el1 && el1.INPUT_ID === el2.INPUT_ID
  el2.ACTIVE_FLAG = inBoth ? 1 : 5
  res.push(el2)
  ix2  
  inBoth && ix1  
}
  • Related