javascript map sorting by value

I am working with an object that has a many-to-one mapping setup:

{
  'a' : 'one',
  'b' : 'two',
  'c' : 'one',
  'd' : 'two'
}

My goal is to transform this object into the following structure:

{
  'one' : ['a' , 'c'],
  'two' : ['b' , 'd']
}

What is the most efficient way to achieve this transformation in javascript? (We are open to using underscore libraries if it simplifies the process) Please note that the objects provided above are simplified examples of the actual data we are working with.

Answer №1

let information = {
  'x' : 'first',
  'y' : 'second',
  'z' : 'first',
  'w' : 'second'
}

let output = {};

for(let property in information) {
    let value = information[property];
    if(!output[value]) output[value] = [];

    output[value].push(property);
}

console.log(output);

Answer №2

If you want to achieve this task, you can utilize the Object.keys() method along with reduce

var data = {'a': 'one','b': 'two','c': 'one','d': 'two'}

var result = Object.keys(data).reduce((res, e) => {
  res[data[e]] = (res[data[e]] || []).concat(e);
  return res;
}, {});

console.log(result)

An alternative approach is to use forEach method and add elements to the newly created object

var data = {'a': 'one','b': 'two','c': 'one','d': 'two'}, r = {}

Object.keys(data).forEach(e => {r[data[e]] = (r[data[e]] || []).concat(e)});
console.log(r)

Answer №3

Here is my solution to the problem at hand. It may not be as intricate as Nenad's, but it gets the job done.

let data = {
  'x' : 'foo',
  'y' : 'bar',
  'z' : 'foo',
  'w' : 'bar'
};

let output = {};

for (let key in data) {
  if (data[key] in output) {
    output[data[key]].push(key);
  } else {
    output[data[key]] = [key];
  }
}

console.log(output);

Answer №4

a concise solution

var obj = {
  'apple' : 'red',
  'banana' : 'yellow',
  'cherry' : 'red',
  'date' : 'brown'
},

result = Object.keys(obj).reduce((prev, current) => {!!prev[obj[current]] ? prev[obj[current]].push(current) : prev[obj[current]] = [current]; return prev},{})

document.write("<pre>" + JSON.stringify(result) + "</pre>");

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

Resolve Redux-Firestore issue #45: Possible Solutions?

I'm facing an issue where deleting a document from Firestore results in my Redux store showing it as null instead of removing it. Even though the document is deleted in Firestore, this inconsistency causes frontend issues because my .map functions can ...

The Material UI read-only rating component fails to update even after the data has been successfully loaded

I have a rating component in my child component, and I am passing data from the parent component through props. However, there seems to be an issue with the MUI rating value not updating when the data is ready for viewing. https://i.sstatic.net/bqSfh.jpg ...

Can an array be made with no defined size limit?

Is it possible to generate an array without any predefined values? I'm a bit confused about how arrays function, but I'm working on an inventory program where I want the user to input products and their respective variables until they're fin ...

What advantages does declaring a backing model "class" that closely resembles the GraphQL "Type" bring when using GraphQL?

I appreciate the Universal Relay Boilerplate for its meticulous organization and thoughtful structure compared to other boilerplates. It seems like they really put a lot of effort into ensuring everything is well-planned from the start, which is not always ...

Steps for running a TypeScript project as a child process within a JavaScript project

I am facing an issue with integrating my Electron app, written mainly in JavaScript, with an Express server project built in TypeScript. When I attempt to create a child process of the TypeScript project within my electron.js file, I encounter TypeScript e ...

Problem encountered with PDFKit plugin regarding Arabic text rendering

When it comes to generating dynamic PDF files, I rely on the PDFKit library. The generation process is smooth, but I'm encountering difficulties with displaying Arabic characters even after installing an Arabic font. Additionally, although the Arabic ...

Why does jQuery function properly in jsfiddle, but not in an HTML file?

I have been troubleshooting repeatedly, but I am unable to figure out why the jQuery code is not functioning as expected. Strangely enough, it works perfectly in jsfiddle! Here is the HTML code: <!doctype html> <html> <head> <meta ch ...

Loop through an array of objects containing nested sub-objects: [ {}, { { { } } }, { } ] using the .map method

Working on creating template cards by parsing some JSON data. However, I am facing an issue with accessing the data returned from my fetch call correctly within the .map method. Here is a snippet of the JSON data: const dataArr = [ { id: 1, name: "Le ...

Convert a JSON string object to a PHP array in PHP

After researching how to decode a string here, I discovered that the process requires the keys to be wrapped in quotes. However, my data does not follow this format. Here is an example: The following data is stored in a .txt file and I am using file_get_c ...

The array sorting function seems to be malfunctioning

It seems like there may be a problem in my main method, but I'm not entirely certain. I am hoping that someone could assist me with this. package testing; import java.util.*; public class mid08 { public static int[] Sort(int[]x) ...

calculate the count field dynamically based on $bucket boundaries in a MongoDB aggregate operation

I'm currently utilizing the Mongo aggregate framework and have a collection structured like this: [ { _id: 123, name: "john", age: 30, fruit: "apple", }, { _id: 345, name: "moore", age: 45, fruit: "mango ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

VueJS - Display a v-html tag that is initially empty but will eventually show content determined by

I have created a recursive component that is capable of infinitely looping over its children At the top of this component is the following line, which serves as the first element within the Vue component: <component class="relative " :is="type || &apo ...

The challenges of updating AngularJS partial templates and handling refresh in 2-way binding

I've encountered an issue with a partial template that's loaded outside of my ng-view, complete with its own controller. Here's a breakdown. Basic template layout <html ng-app="myApp"> ... <div ng-include src="'myPartia ...

Is there a way to stop ng-repeat in AngularJS 1.2 from encoding or escaping my content, or do I have to create my own directive for this?

Is there a way to stop ng-repeat in AngularJS 1.2 from encoding or escaping my content without creating a custom directive? I know that ng-bind-html-unsafe is no longer supported in Angular 1.2, but I'm unsure about its compatibility with ng-repeat. S ...

Unexpected behavior with async/await in Vues.js

Despite appearing to run correctly, the console log indicates that the final result is being output before the inner await/sync. submitForm: function() { console.log("SUBMIT !"); // vee-validate form validation request const makeVali ...

Ways to update a component when the value of a Promise is altered

I am struggling with Vue component re-rendering due to a problem related to consuming data from a Promise. The data is fetched and stored under the specific property chain (visualData.layout.cube...), where I assign values to DATA properties (such as label ...

Inserting an item into a list

Looking for assistance with this particular scenario: { "EekvB3cnwEzE":{ "name":"hi", }, "Brv1R4C6bZnD":{ "name":"yup", }, "kRwRXju6ALJZ":{ "name":"okay", } } I'm attempting to store each of these objects in an array. Howe ...

Tips for bringing a particular tab into focus when a page initially loads

My webpage features custom links (tabs) that display content when clicked. By default, the first tab is selected and its content is shown, while the rest are set to display:none. Clicking on any other link will assign the 'selected' class to it, ...

Consolidate information from various APIs into one centralized location

I am curious to know how one can consolidate data from multiple APIs into a single API. My goal is to retrieve the results from all four res.data endpoints and display them at /coingeckotest address. Even though I am able to see the desired result in the ...