Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comparison between an array and array of arrays to insert missing keys

I’m trying to create a comparison between an array of keys and an array of arrays.
The array of array contains the data as the follwing:

const data = [
  [["id", 1], ["name", "somethign"], ["age", 20]],
  [["id", 20], ["name", "somethign"]],
  [["id", 9], ["age", 10]]
]

An the array with keys, that will always have all the keys I need.

const keys = [
  "id",
  "name",
  "age",
  "nothing"
]

But as you can see in data array, not always all the keys come in the array, what I was attempting to do was, make a comparison between both arrays an add that key that is missing into the data array (in order) as undefined, for example (final result):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const data = [
  [["id", 1], ["name", "somethign"], ["age", 20], ["nothing", undefined]],
  [["id", 20], ["name", "somethign"],["age", undefined] ["nothing", undefined]],
  [["id", 9], ["name", undefined], ["age", 10], ["nothing", undefined]]
]

>Solution :

The following method takes these steps:

  1. Loops over the data in the given order i.e. it will maintain the order of the data.
  2. For each row of the data, it loops over the keys in the order of keys. So within each row, it will keep the order of the keys and keys will be consistent on top of each other.

I prefer null over undefined here but you are free to change it to undefined.

const data = [
  [
    ['id', 1],
    ['name', 'somethign'],
    ['age', 20],
  ],
  [
    ['id', 20],
    ['name', 'somethign'],
  ],
  [
    ['id', 9],
    ['age', 10],
  ],
];

const keys = ['id', 'name', 'age', 'nothing'];

const dataWithMissingKeys = data.map(row =>
  keys.map(key => {
    const foundItem = row.find(element => element[0] === key);
    if (foundItem) {
      return foundItem;
    }
    return [key, null];
  })
);

console.log(dataWithMissingKeys);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading