Combining and forming a distinctive case-sensitive array in JavaScript

Explaining a complex scenario, I have one object or array and one array. My goal is to compare selectedmodel values with mappedmodels. If the value (case insensitive) matches any key in the object, I need to fetch all associated values and push them into the selected model while combining both arrays. The desired output should include all matching values from the object alongside the original selected models.

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

I have already written a solution for this task, but I am seeking ways to optimize performance. Here is the current 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);

}

If you would like to see the code in action, here is the Fiddle.

In my implementation, I am utilizing TypeScript and Underscore.js. Any suggestions on improving this code for better performance would be greatly appreciated.

Answer №1

If you utilize the flatMap method, you can obtain a flattened array containing values for each key in the selectedModels array. Afterward, create a Set to gather a collection of unique models. Finally, use Array.from() to convert the set into 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)

Answer №2

Here are the steps you can take:

    var mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] };
    
    var selectedModels = ['CC605', 'tc76'];
    
    var  desiredOutput;
    
    function combineModelCases(selectedValue){
    if(mappedModels.hasOwnProperty(selectedValue)){
      desiredOutput = [... new Set([...mappedModels[selectedValue], ...selectedModels])]
      return desiredOutput;
     }
    }

  console.log(combineModelCases('CC605'));

To see a working demo, visit: https://jsfiddle.net/wzo4d6uy/2/:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Submit information by utilizing' content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

Attempting to send data to the server with a content-type of 'application/xwww-form-urlencode' is resulting in a failure due to the content type being changed to application/json. var headers= { 'content-type': 'applica ...

What is the recommended service to call in an Angular unit test?

Greetings! Currently, I am in the process of writing unit test cases using Jasmine. My focus lies on interacting with various restful APIs within my components. The specific functionalities I am testing include deletion and addition of users. To facilitate ...

Error Handler: Unable to retrieve the error object when utilized with a promise

I'm currently working on an angular application with a custom error handler implementation. One interesting point to note is that when you have a custom error handler and use an observable with http without catching errors using a catch block, like i ...

having difficulty in transmitting json data using ajax

Struggling to send JSON data to my PHP script via AJAX and it keeps returning NULL as a response. The jQuery script I'm using involves creating a JSON data on a click event and then attempting to send it to the PHP script. Here's a snippet of the ...

Ways to switch out event listener when button is deactivated

I find myself in a situation where I need to switch all unauthorized controls on my UI from a hidden state to a disabled state. Additionally, I want to add a tooltip with unauthorized text and have the control display this text when clicked. While I am ab ...

The screen is cloaked in a dark veil, rendering it completely inaccessible with no clickable

Utilizing Bootstraps modals, here is my current layout. Within the site's header, there exists a "settings" button that triggers a modal containing various options. These options are not tied to the question at hand. The button responsible for displ ...

Running a single test in Angular without using fdescribe or fit

My project has numerous tests that are not being maintained, causing errors when running ng test due to import issues in .spec.ts files. Is there a way to execute a single file test for a service without having to clean up all the tests? Perhaps using Php ...

Using user input to create conditional statements

I'm currently working on a project involving a textbot that outputs information in the console based on user input. It sounds simple, but I've encountered a frustrating problem that I can't seem to solve. There must be an easy fix for this i ...

Exploring the integration of an Angular 4 application with Visual Studio 2017 using dot net core. Techniques for accessing configuration keys from appsetting.json in a TypeScript

I'm currently working on an Angular 4 application using Visual Studio 2017 with .NET Core. I need to figure out how to access configuration keys from appsetting.json in my TypeScript file. I know how to do it in the startup.cs file, but I'm strug ...

Ways to maximize the amount of content contained within a box

My current struggle involves meeting the requirements of my customers. I have a small box (230px x 200px) with an image that will display a list on hover. However, the customer now wants more items in the list than can fit in the box. Scrolling within the ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

Angular 6: showcasing details of selected dropdown items seamlessly on the current page

I am completely new to Angular and I am facing a challenge in displaying another component on the same page. The concept is to select an option from a dropdown menu and then receive detailed information about it below the dropdown on the very same page. No ...

I am looking to include an SVG icon, like a separate React component, within the "title" parameter of a React-Bootstrap Drop Down

Looking to create a header with the Profile icon and Loggedin user positioned on the right side of the Bootstrap Navbar. My goal is to achieve a UI similar to the image linked below without using the Dropdown component. In the image, there are two parts ...

"Troubleshooting the issue of Angular UI-Select failing to display a large

Check out my comprehensive json file containing cities from around the world: download here. Furthermore, take a look at the snippet of html code below: <div class="form-group"> <label class="control-label"> CITY </label> ...

Implementing dynamic title rendering based on image in vue.js

This is the code I'm working with, aiming to display slider data. My goal is that if image[0] appears on the slider, it should return title [0]. I'm quite curious about what could be missing in my setup.code-image ...

How do I configure an Angular project in Nx Workspace to be served as HTTPS?

Currently, I have an nx workspace set up with an Angular project and a NestJS backend. Everything is compiling and functioning properly. Now, the need has arisen to locally host the Angular app using https for development purposes. Typically, I would use t ...

Filtering Key Presses in Quasar: A Comprehensive Guide

Seeking Assistance I am looking to integrate an "Arabic keyboard input filtering" using the onkeyup and onkeypress events similar to the example provided in this link. <input type="text" name="searchBox" value="" placeholder="ب ...

Tips on showing a success notification following form submission in HTML

I have crafted this code utilizing a combination of bootstrap, python, and html. I have omitted the css portion for brevity, but I can certainly provide it if necessary. My aim is to be able to send an email using smtplib and flask, with the added function ...

Some inquiries regarding the fundamentals of JavaScript - the significance of the dollar sign ($) and the error message "is not a function"

Teaching myself JavaScript without actually doing any explicit research on it (crazy, right?) has led to a few mysteries I can't quite crack. One of these mysteries involves the elusive dollar sign. From what I gather, it's supposed to be a con ...