tips on transforming an array object and generating a fresh array

Below is a JavaScript array that I have:

var names = [{name:"high",id:1},{name:"high",id:2}, 
{name:"low",id:1},  {name:"low",id:2},{name:"medium",id:1},{name:"medium",id:2}];

I am looking to transform this array into a new format like the one shown below.

var newArr=[{name:high,items:[1,2]},{name:low,items:[1,2]},{name:medium,items:[1,2]}];

If you have any suggestions on how to achieve this transformation, please let me know.

Answer №1

Underscorejs Library Approach

var obj = {};

_.each(names, function (e) {
    var o = obj[e.name];
    if (o) {
        o.items.push(e.id);
    } else {
        o = {name: e.name, items: [e.id]};
    }
    obj[e.name] = o;
});

var result = _.map(obj, function (e) {return e;});

Pure JavaScript Methodology

var obj = {};
for (var i = 0; i < names.length; i++) {
    var e = names[i];
    var o = obj[e.name];
    if (o) {
        o.items.push(e.id);
    } else {
        o = {name: e.name, items: [e.id]};
    }
    obj[e.name] = o;
}
var result = [];
for (var k in obj) {
    if (obj.hasOwnProperty(k)) {
        result.push(obj[k]);
    }
};

Answer №2

Presenting a straightforward solution without the need for any external libraries.

var uniqueNames = []
for ( var key in names ) {
    var found = findItemInArray(names[key].name,uniqueNames);
    if(found) {                // Another entry with the same name is already in uniqueNames
       var itemsList = found.items.push(names[key].id);    // Add the id to the existing item's list of items
    } else {                   // No other entry with the same name exists in uniqueNames
       var newEntry = {name:names[key].name, items:names[key].id};
       uniqueNames.push(newEntry);
    }
}

I also created this handy function that checks if an item already exists in uniqueNames

function findItemInArray(name,array){
    for(var index in array){
       if(array[index].name === name){
           return array[index];
       }
    return null;
}

Answer №3

Presented below is a solution that does not rely on external libraries:

/**
 * Function to add an object to a set.
 *
 * @param {object} theSet The set where the object will be added.
 * @param {object} theObject The object to be added.
 *
 * @return {object} theSet with theObject added.
 *
 * @note Assumes that theObject.name is the key,
 *       and theObject.id should be in the value array.
 * @note This operates as a callback for Array.prototype.reduce().
 */
function collect(theSet, theObject) {
    if (theSet.hasOwnProperty(theObject.name)) {
        theSet[theObject.name].push(theObject.id);
    } else {
        theSet[theObject.name] = [theObject.id];
    }
    return theSet;
}
var names = [{name:"high",id:5},{name:"high",id:6}, 
             {name:"low",id:1},  {name:"low",id:2},{name:"medium",id:3},{name:"medium",id:4}],
    combinedSet = names.reduce(collect, {}), // Step 1
    final = [],
    key;

// Step 2
for (key in combinedSet) {
    if (combinedSet.hasOwnProperty(key)) {
        final.push(
            {
                "name" : key,
                "items": combinedSet[key]
            }
        );
    }
}

The initial step involves organizing the IDs under their respective object names. This is achieved using Array.prototype.reduce with the callback function collect. The outcome of this process is stored in the combinedSet variable.

In the subsequent step, we convert the set created in Step 1 into the final array, creating objects wherein the keys from the set are assigned to the name attribute and the values are assigned to the items attribute. Since reduce cannot be used here as before, a basic for loop is employed. It's worth noting the inclusion of hasOwnProperty check to mitigate potential issues arising from modifications made to Object.prototype; without this safeguard, unintended items could appear in the set, leading to errors.

Answer №4

If you need a function to group items, consider using underscoreJs groupBy:

Check out this example on jsFiddle

var names = [{name:"high",id:1},{name:"high",id:2}, {name:"low",id:1},  {name:"low",id:2},{name:"medium",id:1},{name:"medium",id:2}];

console.debug(_.groupBy(names, 'name'));
// This will return an object with grouped arrays based on the 'name' key

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

The interface remains static even after the property has been modified

There is a function in my codebase called getData() that fetches data from an API. I am trying to call this function from a different component, which I will refer to as MainComponent and AnotherComponent for the sake of clarity: import MainComponent from ...

Could this be considered a typical trend - opting to return data instead of a promise?

I recently came across a new approach while reading 'Mean Machine'. Typically, I have always been taught to return a promise from a service to the controller and then handle it using .success or .then. In this case, the author is directly retur ...

Issue with unapplied nullable type during export操作

I'm struggling to understand why my nullable type isn't being applied properly Here's an illustration interface Book { name: string; author: string; reference: string; category: string; } async function handleFetch<T>(endpoin ...

The animation speed of the jQuery hashchange event is set to zero, causing the animation

I'm facing an issue with jQuery where my animation inside a hashchange event is not smooth; it happens instantly when triggered. I'm looking for a way to make the animation smoother. jQuery( document ).ready(function() { jQuery(window).on(&a ...

Issue with Tooltip Position when Scrolling Sidebar is causing display problems

My goal is to create a Sidebar with Tooltip attached to its <li> elements similar to this example: Screenshot - Good Tooltip However, I am facing an issue where the position of the Tooltip breaks when scrolling to the bottom of the sidebar, causing ...

I can't get the websocket to automatically reconnect unless I refresh the browser tab

Currently, I have a web server running websockets on an ESP8266. The operations are smooth on both the client and server sides, with data being sent and received. However, when the server side disconnects due to a power cycle or code upload, the client (Ch ...

"Encountering a problem with a function showing an undefined error

Trying to incorporate a slider feature into my application led me to reference this w3schools sample. However, upon loading the page, the images briefly appear before disappearing. Additionally, clicking on the arrow or dots triggers an error stating: U ...

What do cross-domain requests, cross-domain attacks, and cross-domain protocols entail?

Can anyone provide clarification on the concepts of cross domain requests, cross domain attacks, and cross domain protocols as they relate to the AJAX terminology? ...

Experiencing a crash immediately following the implementation of the operator new[] in C++

I'm dealing with a memory allocation issue in my code. Specifically, when working with arrays v1 and v2 in my Vector class, I encounter problems with memory allocation during the copying process. How can I resolve this issue? Below is the relevant cod ...

I would appreciate your assistance with the hide button

Is there a way to hide a button after clicking on it? I would greatly appreciate your help! ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

Removing the dollar sign and retaining only the numerical values in an array using JavaScript

Using the code snippet below, I am attempting to retrieve elements by their class name in JavaScript and save them in an array. This is the current output I receive: "I received this output from the initial prices array $30.00, $20.00, $40.00" My inquiry ...

JavaScript - Separate Artist and Title

In the code snippet below, I am using a Parser script to extract metadata from a live streaming radio station: const Parser = require('../src'); const radioStation = new Parser('http://stream.com/live_32.aac'); radioStation.on(' ...

Assign the value from JavaScript to the element with the "ng required" attribute, without resetting frm.$error.required to false

My situation involves using a button with ng-style that relies on frm.mybtn.$error.required as follows: ng-style="frm.mybtn.$error.required?{'border-color':'#a94442'}:''" I am updating the value of the button from JavaScript ...

The functionality of res.status().send() appears to be malfunctioning when used within a Promise

I am currently working on a code that involves checking authorization from two different API calls within a promise.all method. If any of the authorizations fail, I want to throw the respective res.send method as an error. However, I keep encountering an " ...

Utilizing the model value either by directly accessing it or by passing it as a parameter to a function from the

After exploring both options, I am still unsure which one is more technically superior in terms of functionality. One method involves passing a model value from the front end HTML to a function by calling ng-click. View: <input type="text" ng-model= ...

Redirect link depending on JSON callback information

I experimented with utilizing JavaScript to automatically redirect website visitors based on their country. The code snippet below demonstrates how the visitor's IP is checked to determine their country, such as CN for China, and then redirects them ...

Executing a function without a callback within an Async library

I am facing an issue with this particular example mentioned in the Async documentation: async.map(['file1','file2','file3'], fs.stat, function(err, results) { // results is now an array of stats for each file }); In this ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

JavaScript redirecting without refreshing the page

Currently, I am faced with a dilemma involving an Ajax function that calls a remote site, saves data to a database, and then needs to refresh the current page to display the new information. The complication arises from the fact that tabs are being utilize ...