Home > OS >  Compare two arrays and check if have a same key's
Compare two arrays and check if have a same key's

Time:09-27

I need a compare two arrays and if I have differents keys, update both with same keys and 0 if not exist key before.

Eg.

let obj1 = [
{"type": "Riesenslalom","total": 2862},
{"type": "Slalom", "total": 362 },
{"type": "Super-G", "total": 579 }];

let obj2 = [
{"type": "Riesenslalom","total": 2218},
{"type": "Slalom","total": 448},
{"type": "Wall", "total": 133 }
];

My goal

let obj1 = [
{"type": "Riesenslalom","total": 2862},
{"type": "Slalom", "total": 362 },
{"type": "Super-G", "total": 579},
{"type": "Wall", "total": 0 }
];

let obj2 = [
{"type": "Riesenslalom","total": 2218},
{"type": "Slalom","total": 448},
{"type": "Super-G", "total": 0 }
{"type": "Wall", "total": 133 }
];

I tried different ways but can't solve this problem :(

Cheers

CodePudding user response:

Pass in the arrays to a function - the first that you want to update, the second that you want to update from, and loop over the objects in the first array. If the type value isn't found in an object in the second array update it with an "empty" object.

Return the updated array sorting it by type if required.

Repeat the process by swapping the arrays around in the arguments.

const arr1=[{type:"Riesenslalom",total:2862},{type:"Slalom",total:362},{type:"Super-G",total:579}],arr2=[{type:"Riesenslalom",total:2218},{type:"Slalom",total:448},{type:"Wall",total:133}];

function update(updateTo, updateFrom) {
  for (const { type } of updateFrom) {
    const found = updateTo.find(obj => obj.type === type);
    if (!found) updateTo.push({ type, total: 0 });
  }
  return updateTo.sort((a, b) => a.type.localeCompare(b.type));
}

console.log(update(arr1, arr2));
console.log(update(arr2, arr1));

  • Related