Home > Net >  compare two dictionaries in google apps script
compare two dictionaries in google apps script

Time:01-10

I have two dictionaries

old = { C43: 'X13',
  C59: 'X13',
  C75: 'X14',
  C91: 'X14',
  C107: 'X16',
  C123: 'X17' }

The ```old`` can have any number of entries.

and

new = { C139: 'X17' }

The ```new`` can have any number of entries.

I am trying to match the values of both dictionaries and move the keys from old wherever the values in old and new match.

The output to be in a new array as,

new_array = [ C123 ]

I tried the below, but I am not doing it right, Please guide

var new_array = [];
        for (var key in old) {
          var check_matching_value = old[key] === new[key]
          if (check_matching_value == true) {
            new_array.push(key);
          }
        }
        console.log(matchingKeys);

CodePudding user response:

Use Array.filter(), like this:

function test() {
  const oldDict = {
    C43: 'X13',
    C59: 'X13',
    C75: 'X14',
    C91: 'X14',
    C107: 'X16',
    C123: 'X17',
  };
  const newDict = { C139: 'X17', };
  const newValues = Object.values(newDict);
  const newArray = Object.keys(oldDict)
    .filter(key => newValues.includes(oldDict[key]));
  console.log(newArray); // "C123"
}
  • Related