'Recursively replace item in array based on another array's values

Sorry for the noob question, but I'm new at JavaScript.

I have these arrays:

const files = ['pt_rBR.xlf', 'it.xlf', 'es.xlf']
const language_map = [{'file': 'de.xlf', 'lang': 'de_DE'},{'file': 'es.xlf', 'lang': 'es_ES'},{'file': 'it.xlf', 'lang': 'it_IT'},{'file': 'pt-rBR.xlf', 'lang': 'pt_BR'}]

What I'd like to do is to create a new array where the elements of array "files" are replaced by the values of array "language_map" - the keys of "language_map" are the elements of "files", so like:

languages = ['pt_BR', 'it_IT', 'es_ES']

How do I set out to do so? I know that I can loop through the elements of "files" like so:

for (const element of files) { 
    console.log(element);
}

but how do I do the actual replacement and creation of the new array?

Thank you



Solution 1:[1]

Something like the below should do what you need.

const files = ['pt-rBR.xlf', 'it.xlf', 'es.xlf']
const language_map = [{'file': 'de.xlf', 'lang': 'de_DE'},{'file': 'es.xlf', 'lang': 'es_ES'},{'file': 'it.xlf', 'lang': 'it_IT'},{'file': 'pt-rBR.xlf', 'lang': 'pt_BR'}]
const languages = [];
var k=0;

// POPULATE ARRAY
for (let i = 0; i < files.length; i++) {
  for (let j = 0; j < language_map.length; j++) {
    if(files[i]==language_map[j]['file']) {
     languages[k]=language_map[j]['lang'];
     k++;
    }
  }
}

// OUTPUT ARRAY
for (let z = 0; z < languages.length; z++) {
  alert(languages[z]);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dean O'Brien