Reputation:
i want to modify array based on its values using javascript.
what i am trying to do?
these are possible values in the array
['cd', 'md', 'Sl']
but the array could be empty or might not contain all above 3 values.
some examples could be
['cd', 'md']
[]
['cd']
['Sl']
..... so on
now when the array has 'cd' it should be replaced with 'cad'. similarly if it has 'md' it should be replaced by 'modular detection' and 'Sl' with 'Some logic'
so the expected output for array
['cd', 'md', 'Sl'] is
['cad', 'modular detection', 'Some logic']
could someone help me do this. i am new to programming. thanks.
Upvotes: 0
Views: 47
Reputation: 9713
By using replace method
const input = ['cd', 'md', 'sl', 'md', 'cd', 'sl'];
var mapObj = {
'cd': 'cad',
'md': 'modular detection',
'sl': 'Some logic'
};
const output = input.toString().replace(/cd|md|sl/gi, (x) => mapObj[x]).split(",");
console.log(output);
Upvotes: 1
Reputation: 3178
We can map our key:string values in a dictionary, then map
our array to that dictionary.
const dict = {
'cd': 'cad',
'md': 'modular detection',
'sl': 'Some logic'
}
const input = ['cd', 'md', 'sl', 'md', 'cd', 'sl']
const output = input.map(key => dict[key])
console.log(output)
Upvotes: 4