0

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.

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.