JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below.

let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal']

I expect the output to be as follows;

output={
    animal: ['monkey', 'donkey'],
    human: ['John', 'Rob']
}

Answer №1

Check out this clever approach utilizing String#split and Array#reduce:

let animals = ['monkey: animal','John:human', 'Rob:human', 'donkey:animal'];

const categorizedAnimals = animals
  .map(item => item.split(':').map(i => i.trim()))
  .reduce((acc, [name, type]) => {
    if (acc[type]) {
      acc[type].push(name);
    } else {
      acc[type] = [name];
    }
    return acc;
  }, {});

console.log(categorizedAnimals);

Answer №2

Conventional method of consolidating data:

const dataSet = ['monkey: animal','John:human', 'Rob:human', 'donkey:animal'];

const finalResult = dataSet.reduce((accumulator, item) => {
    const [value, key] = item.split(':').map(e => e.trim());
    accumulator[key] ??= [];
    accumulator[key].push(value)
    return accumulator;
}, {});

console.log(finalResult);
.as-console-wrapper { max-height: 100% !important; top: 0 }

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

Unable to turn off X-Powered-By: Express

After attempting to use app.disable("x-powered-by"); without success, I came across some helpful posts on the topic: how to remove X-Powered-By in ExpressJS Can't get rid of header X-Powered-By:Express I am using "express": "^4.16.4" as backend a ...

Tips for setting up a scheduled event on your Discord server using Node.js

Hello fellow programmers! Recently, I've been working on a Discord bot using discordjs sdk. I'm trying to implement a feature where the bot creates an event every week. I went through the discordjs guide and checked the discord api documentati ...

Angular version 4 is used to retrieve deeply nested JSON data

How do I extract data from a nested JSON file? Here is an example of the JSON structure: { "user1": { "name": "john", "surname": "johnsson" }, "user2": { "name": "Jacob", "surname": "Jacobsson" } } I want t ...

Slider with Dual Images: A Visual Comparison

I'm currently working on a webpage that features before and after images using a slider based on mouse movement to display both pictures. I am trying to incorporate multiple sliders on the same page but have been facing difficulties in getting them to ...

Issue with displaying the file-field in Django admin after upgrading from Django 2.1 to version 3

Since upgrading from Django 2.1 to 3, the file field in Django admin is now displaying as "loading". https://i.sstatic.net/8JDWu.png An error is appearing in the console. https://i.sstatic.net/RCgwt.png https://i.sstatic.net/78YtG.png Previously, ther ...

"When a Vuex mutation modifies the state, the computed property fails to accurately represent the changes in the markup

I've encountered a perplexing issue with using a computed property for a textarea value that hasn't been addressed in a while. My setup involves a textarea where user input is updated in Vuex: <textarea ref="inputText" :value="getInputText" ...

To include a Material Icon in your React-Toastify notification

This is an example of code located in a specific folder. While trying to incorporate a material Icon, an error has been encountered. 'React' must be in scope when using JSX import { toast } from 'react-toastify'; import ErrorIcon from ...

Pressing the HTML button will reveal the cart details in a fresh display box

I have been working on setting up a button to display the items in the shopping cart. I have successfully created the cart itself, but now I am facing the challenge of creating a button called showYourCart that will reveal a box containing the cart detai ...

JavaScript obtain scroll position of a child element

I have a setup that looks something like the following: <div> <div id="scrollID" style="height:100px;"> content here </div> </div> <script> document.getElementById("myDIV").addEventListener("touchstart", m ...

Guide on sending a JavaScript variable as a URL parameter in Django

I need to pass a radio ID to my view, but I'm struggling with how to do it using the GET method in the URL: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/ma ...

Building an array of ids that contain the checkbox type using jQuery: What's the best way?

Below is the HTML snippet I am working with: <!-- Parent checkbox code goes here --> <input id="ckbCheckAll" class="custom-check ez-hide" type="checkbox" name=""></input> <!-- Child checkbox codes follow --> <input id="practice_ ...

What is the method for altering the icon within the KeyboardTimePicker component in material-ui-pickers?

Is there a way to customize the icon displayed in the KeyboardTimePicker component? I've looked into KeyboardButtonProps and InputAdornmentProps but I'm still unsure of how they can assist me... Link to my customized KeyboardTimePicker ...

Learn to display multiple collections of data on a webpage using Node.js and MongoDB

Struggling with displaying multiple collections on my webpage. After extensive research, I keep encountering an error message saying "Failed to look up view in views directory." Here is the code snippet causing the issue: router.get('/', functio ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

Substitute the string (3-11-2012) with a different date layout (3 november 2012)

Can anyone guide me on how to convert text strings like '11-1-2012' into date strings like '11 januari 2012'? I've been looking for a solution, but haven't found exactly what I need. The month names should be in Dutch. I attem ...

How to avoid the need to wrap all setState calls with #act in React 18?

One issue I encountered was when upgrading from React 17 to 18, ReactDom render became asynchronous. To handle this, I needed to use #act to wrap the ReactDom render. However, React also required that all setState calls be wrapped with #act. If not done, ...

Implementing a peculiar timing mechanism with the integration of socket.io, jQuery Mobile, and the socket.emit() function

Currently in the process of working with cordova and node.js socket.io, I encountered a peculiar issue with socket.emit(); The following code fails to enter 'room', despite having correct coding: client-side jsfile.js //Two global variables fo ...

What is the best way to remove the hover effect from a specific element within a div?

I am looking to achieve a specific hover effect where the white part does not darken when hovering over a certain element within its child elements. Here is the HTML code I have: <div className= {css.searchBarDiv}> <div className={css.searchBar ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...