Ad

Merge And Create An Unique Case Sensitive Array In Javascript

It's a complicated scenario but will try to explain as much as possible. I have one object or arrays and one array. Now i have to compare selectedmodel values with mappedmodels, if the value(Case insensitive) matches with that object then fetch all the values of it and push it into selected model and combine both. Hope the example will clear what i am trying to achive.

var mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] };
var selectedModels = ['CC605', 'tc76'];
var desiredOutput = ["CC605", "tc76", "cc605", "cC605"];

I already wrote a solution to achieve it but i need a better code in terms of performance. Here is the solution:

function combineModelCases(selectedModels) {
const modelCases = [];
selectedModels.forEach(elm => {
  const existingModels = mappedModels[elm.toUpperCase()];
  if (existingModels) {
    for (const key of existingModels) {
      if (elm.toUpperCase() !== key) {
        modelCases.push(key);
      }
    }
  }
});
return selectedModels.concat(modelCases);

}

Here is Fiddle

I am using typescript and underscore js for your references. Any help would be very helpful.

Ad

Answer

You could use flatMap to get a flattened array of values for each key in selectedModels. Then, create a Set to get a unique collection models. Use Array.from() to convert the set to an array.

const mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] },
      selectedModels = ['CC605', 'tc76'];

const models = selectedModels.flatMap(m => mappedModels[m] || []),
      unique = Array.from(new Set([...selectedModels, ...models]));

console.log(unique)

Ad
source: stackoverflow.com
Ad