Creating a visual representation from an array of strings to produce a

My goal is to organize a list of server names into a map using a specific logic.

For instance, with names like:

"temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"

They would be mapped as:

{
  a: [
    "temp-a-name1",
    "temp-a-name2"
  ],
  b: [
    "temp-b-name1",
    "temp-b-name2"
  ]
}

The key will always be the first letter after the dash "-".

Although my JavaScript knowledge is limited, I have achieved this by taking a simple approach. However, I am curious if there is a more efficient and typical JavaScript way to accomplish this task.

const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];

let map = {};
let key;
for (const server of servers) {
  key = server.charAt(server.indexOf("-") + 1);
  if (key in map) {
    map[key].push(server);
  } else {
    map[key] = [server];
  }
}

Answer №1

To achieve this task, one can utilize the reduce() method as shown below:

let servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];

let map = servers.reduce((acc, server) => {
  let key = server.charAt(server.indexOf("-") + 1);

  if (acc[key])
    acc[key].push(server);
   else
    acc[key] = [server];
    
  return acc;
}, {})

console.log(map)

Answer №2

Give this a shot:

const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];
const result = servers.reduce((acc, cur) => ({
    ...acc,
  [cur.split('-')[1]]: (acc[cur.split('-')[1]] || []).concat([cur]),
}), {})
console.log(result);

This qualifies as being quite "javascripty," don't you think?

Answer №3

To retrieve the key, I would utilize the reduce method. One way to extract the key could involve using .split('-')[1].

const items = ['temp-a-item1', 'temp-a-item2', 'temp-b-item1', 'temp-b-item2'];
const dictionary = items.reduce((dictionary, item) => {
  const key = item.split('-')[1];
  const itemsWithKey = dictionary[key] || [];

  return { ...dictionary, [key]: [...itemsWithKey, name] };
}, {});

console.log(dictionary);

Answer №4

To implement a similar concept using the new Map data structure, you can follow this example:

const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];

const map = new Map();

servers.forEach(item => {
  const key = item.split('-')[1];
  const value = map.get(key) || [];
  value.push(item);
  
  map.set(key, value);
});

// OUTPUT TO CONSOLE
for (var [key, value] of map.entries()) {
  console.log(key + ' = ' + value);
}

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

Guide: Highlighting a selected link in Navigation without redirecting the page can be achieved in AngularJS by utilizing

I have a list of links that I want to be able to highlight when clicked without redirecting to the page. Below is the code snippet: HTML <ul class="nav nav-list"> <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...

My SF2 app is experiencing issues with AngularJS integration

I am currently developing a straightforward API using Symfony2 and now I am experimenting with integrating AngularJS into my bundle to visualize the results of my API calls. How can I effectively implement AngularJS? I initiated a bundle via app/console ...

The function is not being executed when using $scope.$apply()

I am in need of a customized click directive that can execute the passed code using scope.$apply(). $(elem).on('click', function(){ scope.$apply(attrs.wdClick); }); Everything works smoothly when I pass something like wd-click="something = ...

Remove a particular item by clicking on the icon in React.js

I'm currently working on a React JS exercise for creating a "To Do List". I am facing an issue where I want to delete individual tasks by clicking the trash icon, but my current code deletes all tasks at once. Can someone help me understand how to ach ...

Tips for enhancing the fluidity of animations after removing an item from a list

I'm working on a project where I have a list of elements that are removed with an animation when clicked. However, I noticed that when one element is removed, the rest of the elements just jump up instead of smoothly transitioning. Is there a way to m ...

Warning: An unhandled promise error occurred due to a validation error

I've been facing an issue for the past few days. Currently, I'm diving into learning the MEAN stack, but while trying to create a user on MongoDB using Mongoose schema, I encountered this problem: (node:93337) UnhandledPromiseRejectionWarning: ...

Attempting to conceal a div element along with its contents using AngularJS

I am attempting to use AngularJS to hide a div and its contents. I have defined a scope variable initialized as false and passed it to the div in order to hide it. However, the div is still visible along with its content. <script type="text/javascr ...

Developing a web service that can receive XML data in string format

In my attempt to develop a webservice, I encountered a challenge involving allowing the client to send 3 string parameters - Username, Password, and XML_In. These parameters are then processed by a Stored Procedure that generates an XML string which is sen ...

Color Your Plone Website with a Custom JavaScript Colorscheme

Currently, I have implemented a custom theme by registering the javascript in the skin.xml file and then creating a specific folder within the browser to store the script. Below is the script shared by one of the users: $(document).ready(function(){ ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

Steps to refresh a .ejs page with updated information following an ajax request

I am in need of re-rendering my homepage.ejs with new data on the server side following an ajax request. Although I am aware that you can somehow re-render the elements in the ajax callback, I am interested in finding out if it is possible to simply re-ren ...

Decoding a formatted string

Here is a string that needs parsing: const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");' The goal is to generate a JSON structure like this: [{id: 'a', map: 'b'}, {id: 'foo', map: 'bar&a ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

What is the way to create the appearance of a hand or arrow hovering over my "X" while I am closing out my Div using jQuery?

Hey there, I've got a handle on closing the div using a "p" tag in jQuery. The code snippet for that is provided below. However, I'm looking to change the cursor over the "X" to an arrow or hand symbol, similar to what you'd see with an "a" ...

Populate the dropdown menu with data from a JSON file

Recently, I created a custom JSON file and wanted to populate a select>option using this data. However, I encountered an error message saying: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/.../p ...

Refreshing ng-model within a radio input

Currently, I am utilizing a jQuery library for radio/checkbox components. Although I am aware that combining jQuery with Angular is not ideal, the decision to use this particular library was out of my control and cannot be altered. One issue I have encount ...

Tips on integrating Codrops tutorial codes into a SilverStripe website project

Exploring the vast array of tutorials and code examples on the Codrops site has been an enlightening experience. Codrops Website I'm eager to incorporate some of these resources into my SilverStripe projects as well. SilverStripe CMS After learning h ...

Changing a button's text in Vue.js when holding a keyboard modifier - how to do it!

While working with Vue, I am attempting to modify a button's behavior when the Shift key is pressed. Adjusting the behavior of the click event was straightforward: @click.exact="goForward" @click.shift="goBackward" However, I am f ...

Creating a single loop in Javascript to populate two dropdown menus with options

Is there a way to populate two dropdown menus in JavaScript with numbers using the same for loop? Currently, only one is being populated, specifically the last one. for (var i=1; i<10; i++) { var option = document.createElement("option"); option. ...