JavaScript: Organizing values based on their case sensitivity

Imagine a scenario where we have models ABC23x, ABC23X & abc23X all referring to the same model. These model names are retrieved from API endpoints.

Now the UI has two tasks:

  • Display only one model name (ABC23X)
  • When calling the REST API, we need to send all possible values ([ABC23x, ABC23X, abc23X])

I am seeking assistance in implementing this feature. I attempted using MAP but it did not work as expected.

let models = ['tc75X', 'TC75X', 'tc75x', 'TC75x', 'TC76x', 'TC77Y'];
let mappedModels = new Map(models.map(s => [s.toUpperCase(), s]));

console.log(mappedModels);

Here is the fiddle

I am using Angular 6. Any assistance or suggestions would be greatly appreciated.

Answer №1

The problem you're facing is that each new key is replacing the old one. Here's a breakdown of what's happening:

  1. When you get 'tc75X', it becomes the key 'TC75X' and gets added to the Map as 'TC75X' -> ['tc75X']
  2. Then, when you get 'TC75X', it also becomes the key 'TC75X' and gets added to the Map as 'TC75X' -> ['TC75X']

As a result, you end up with only one value instead of two.

Instead of overwriting keys, you should group them together like this:

  1. If the current model key doesn't exist in the Map yet, add it.
  2. Include the current value under the corresponding key in the Map.

let models = ['tc75X', 'TC75X', 'tc75x', 'TC75x', 'TC76x', 'TC77Y'];

let mappedModels = models.reduce((map, modelName) => {
  const normalisedKey = modelName.toUpperCase();
  
  //1. Add entry if not present
  if (!map.has(normalisedKey)) {
    map.set(normalisedKey, []); 
  }
  
  //2. Add to entry for this key
  map.get(normalisedKey).push(modelName);
  
  return map;
}, new Map());

for(let [key, value] of mappedModels) {
  console.log(key, "->", value);
}

Answer №2

An example of how this can be approached is provided below. Initially, a key is created followed by the creation of a new array if the key does not already exist in the map. Subsequently, the value is assigned to the new array.

const devices = ['iPhone X', 'iphone x', 'IPHONE X', 'ipad pro', 'iPad Pro'];
const mappedDevices = new Map();

for (const device of devices) {
  const key = device.toUpperCase();
  let set = mappedDevices.get(key);

  if (!set) {
    set = [];
  }

  set.push(device);
  mappedDevices.set(key, set);
}

console.log(mappedDevices);

Answer №3

If you want to store your models in a unique way, you can use an object for that purpose. Each key in the object represents the uppercase version of a model, and the corresponding value is an array containing all versions of the model with different casings.

const models = ['tc75X', 'TC75X', 'tc75x', 'TC75x', 'TC76x', 'TC77Y'];

const modelMap = models.reduce((result, currentModel) => {
  const uppercasedModel = currentModel.toUpperCase();
  
  if (!result[uppercasedModel]) {
    result[uppercasedModel] = [currentModel];
  } else {
    result[uppercasedModel].push(currentModel);
  }
  
  return result;
}, {});

console.log(modelMap);

Answer №4

let carModels = ['tc75X', 'TC75X', 'tc75x', 'TC75x', 'TC76x', 'TC77Y'];

let mappedCarModels = carModels.reduce((acc, model) =>{
    let upperModel = model.toUpperCase(); 
acc[upperModel] = acc[upperModel] || [];
acc[upperModel].push(model);
return acc
}, {});

for (let [key, value] of Object.entries(mappedCarModels)) {
  console.log(`${key}: ${value}`);
}

This code snippet demonstrates the use of the reduce method to organize and map car models based on their uppercase versions.

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

Establishing a path for a post request in a Node.js application

While setting up a basic registration page, I encountered an error when trying to establish a route for the post request of the user credentials. node:_http_outgoing:648 throw new ERR_HTTP_HEADERS_SENT('set'); ^ Error [ERR_HTTP_HEADERS_ ...

Using the Vue.js Spread Operator in place of Vue.set or Vue.delete

I'm exploring ways to utilize the spread operator for adding or removing object properties in a manner that preserves reactivity. Within a Vuex mutation, this code snippet is successful: Vue.set(state.sportTypes.sports, sportName, sportProperties) H ...

Creating an array of JSX elements or HTMLElements in a React TypeScript rendering

Currently in the process of developing a custom bootstrap card wrapper that allows for dynamic rendering of elements on the front and back of the card based on requirements. Here is the initial implementation: import React, { useState, ReactElement } from ...

"Implementing Scrollify.js to dynamically add a class to the current section

I'm attempting to dynamically add an 'active' class to the current section on a page using scrollify.js. While I can retrieve the index value, I am struggling to get the section id or class. How can I obtain the id or class of the current s ...

Is the Vue-portal enabled conditionally?

I am looking to include some additional information in the navbar (parent component) using Vue Portal. So, within a component, I can use the following code: <portal to="navbar"> <b-button>Some option</b-button> </portal&g ...

Two-way data bindings trigger the digest() function to iterate 10 times

I'm facing issues with angular binding and my experience level in this area is limited. I will be posting all related questions here. I have a piece of angularjs code that is triggering 10 digest() cycle reached errors. After researching similar posts ...

Is it possible to conceal any spans that are in close proximity to the cursor when hovered over?

Currently, I am working on a project that involves multiple spans placed side by side, with each span containing a letter of the text. My aim is to create a functionality where hovering over one of these spans will not only hide that particular span but al ...

Ways to present a Nuxt page as a reply from an express route

How can I achieve a similar functionality to res.render on a Nuxt page? The project is using the nuxt-express template, which combines Nuxt and Expressjs. Although Nuxt provides nuxt.render(req, res) and nuxt.renderRoute, I am having trouble making it wo ...

Leveraging jQuery for handling button functionality and making asynchronous requests

I am relatively new to working with jQuery, and while there are plenty of resources available on how to bind buttons, I find that my current setup is a bit more complex than what's typically covered. My situation involves: -Using Django to populate ...

Sending a PHP string formatted as JSON to be processed by jQuery

When attempting to echo a string with a JSON structure, I am encountering issues with the jQuery ajax post not parsing it correctly. My question is whether this string will be recognized as JSON by the jQuery json parse function when echoed in a similar ma ...

Is there a method to obtain the image path in a similar manner to item.src?

I am currently utilizing freewall.js, which can be found at The images will be generated dynamically. Therefore, the HTML structure will look like this: <div class="brick"> <img src="" width="100%"> </div> Here is the corresponding J ...

Ways to transmit additional arguments to RxJS map function

When working with an Angular application, I utilize HttpClient along with RxJS operators to execute various API calls. One example of this is shown below: return this.httpClient.put(url, JSON.stringify(treeOptions)) .pipe( map(this.extract ...

Managing status in Angular applications

I am currently working on a project using Angular 7 and I have the following code snippet: public deleteId(pId){ return this.http.delete<any>(this.deleteUrl(pId), {observe: 'response'}) .pipe(catchError(this.handleError)); } I ...

Exploring the resolution of unit test for an Angular Bootstrap modal using the John Papa ViewModel style

A custom ModalService has been created to display two different types of dialogs, CancelDialog and ErrorDialog, based on the parameter passed to the service. For example, the following code will show an ErrorDialog: ModalService.openModal('Analysis ...

"Vue3 offers the ability to return a multi-layer object through the Provide-Inject

While implementing provide-inject in my personal project, I encountered an issue where the value returned by inject() was a RefImpl Object. This meant that I had to access the actual value using inject().value.value instead of just inject().value. Here is ...

Having trouble configuring the sticky-footer correctly

Currently enrolled in a web development course on Udemy, I am facing an issue with the footer on my webpage. Even after setting its CSS position to relative, the footer overlaps the content when more data is added. However, removing this positioning causes ...

Using HTML to design interactive buttons that can send API requests and display their current status

Seeking assistance with creating buttons to control a remote light's ON and OFF states while reflecting their status as well. The specific http API calls for the light are necessary to toggle its state. Turn On = http://192.168.102.22:3480/data_requ ...

I am currently experiencing difficulties with react-navigation as I am unable to successfully pass a parameter through a nested navigation stack

Despite attempting all recommended methods to pass a parameter through a nested navigator in react-navigation, I have hit a dead end. Previous solutions and documentations did not yield results, and even chatGPT failed to provide assistance. So now, with h ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

Issues arise during the deployment of Angular7 production build when passing through the Bitbucket package manager

I am working on a project to create a system that allows Angular components to be reused across multiple applications via BitBucket. Currently, I have the following setup: BitBucket Repo A - This repository stores the node module. The module is develope ...