0

I have project in which I need to develop a specific calculator. By far everything is good but now I am stuck in one problem. I have an array of the object containing letter as key and its value as below

valueList = [{a:5}, {b:3}, {c:8}, {d:6}]

and I have an input element where user can type specific characters like this

input = "a+b-c"

how do I modifie the above string to the new string that contains values of alphabets from valueList like

newVar = "5+3-8"

I have tried below solution with no far success

const final = input.split("").map((variable) => {
  return valueList.forEach((element) => {
    if (variable === Object.keys(element)[0]) {
      return Object.values(element)[0];
    } else {
      return variable;
    }
  });
});
console.log(final);

1 Answer 1

1

First turn the valueList into an object with multiple properties, rather than an array of objects with single properties. Then use a regular expression to match any of the keys of the objects, and use a replacer function to look up the matching value on the object:

const valueList = [{a:5}, {b:3}, {c:8}, {d:6}];
const obj = Object.assign({}, ...valueList);
const input = "a+b-c";

const pattern = new RegExp(
  Object.keys(obj).join('|'),
  'g'
);
const output = input.replace(pattern, match => obj[match]);
console.log(output);

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.