Wrap all temporary array elements of the same type within an object

Extracted from a json api, the following snippet of content showcases various titles and content types:

contents: [
 { title: "some title", content_type: 2 },
 { title: "some title", content_type: 2 },
 { title: "some title", content_type: 1 },
 { title: "some title", content_type: 2 },
 { title: "some title", content_type: 1 },
]

To simplify data manipulation tasks, it is suggested to group consecutive items with the same type into separate arrays as illustrated below:

contents: [
 type2: [
   { title: "some title", content_type: 2 },
   { title: "some title", content_type: 2 }
 ],
 { title: "some title", content_type: 1 },
 { title: "some title", content_type: 2 },
 { title: "some title", content_type: 1 },
]

Note that single instances like the last content type 2 should remain ungrouped for efficient processing. The challenge lies in implementing this grouping method effectively while ensuring easy removal of wrappers when needed for server updates.

Answer №1

let data= [
 {title: "hello world", type: 2},
 {title: "goodbye world", type: 1},
 {title: "greetings world", type: 2},
 {title: "farewell world", type: 1}
];

let groupByType = function(data) {
    let groupedData = {};
    data.forEach(function(item) {
        let key = 'type' + item.type;
        if (!groupedData[key]) {
            groupedData[key] = [];
        }

        groupedData[key].push(item);
    });
    return groupedData;
};

let groupedData = groupByType(data);

console.log(groupedData);

let ungroupByType = function(data) {
    let arr = [];
    for (let key in data) {
        arr = arr.concat(data[key]);
    }
    return arr;
};

let ungroupedData = ungroupByType(groupedData);

console.log(ungroupedData);

This code organizes the data by type:

{ 
   type2: [ 
     { title: 'hello world', type: 2 },
     { title: 'greetings world', type: 2 } 
   ],
   type1: [
     { title: 'goodbye world', type: 1 },
     { title: 'farewell world', type: 1 }
   ]
}


[ 
  { title: 'hello world', type: 2 },
  { title: 'greetings world', type: 2 },
  { title: 'goodbye world', type: 1 },
  { title: 'farewell world', type: 1 }
]

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

Is it feasible to trigger a dialog box by clicking on a textField within MaterialUI?

Is there a way to create a clickable textField that opens a dialog box for users to input more text? I'm specifically looking for a solution using MaterialUI. Currently, I have a workaround where a button is displayed to open the dialog box instead o ...

Converting JSON responses into Dictionary format in Swift: A Guide

Is there a way to convert the JSON response containing numerous keys in the message field into a format that can be assigned to a variable of type [AnyHashable: Any]? JSON { "content": { "message": { "greet": "Hello world", ...

The npm outdated -g command is producing an error message that states "Unable to read the length property of undefined"

I am currently facing an issue while trying to check the version status of my npm installed global packages. When I run the command npm outdated -g --depth=0 in the terminal, I encounter the following error: npm ERR! Cannot read property 'length&apos ...

skip every nth element in the array based on the specified value

The Challenge I'm currently working on a graph that relies on an array of data points to construct itself. One major issue I've encountered is the need for the graph to be resizable, which leads to the necessity of removing certain data points ...

Issue occurs when trying to access the 'set' property of an undefined variable, leading to an error message stating "Cannot read property 'set' of undefined" while using 'this

I'm facing an issue while setting up basic cookies for my Vue project. When I try to set a cookie, I encounter the following error. My package.json file indicates that I am using vue-cookies version ^1.7.4. The error message occurs when I click the bu ...

The essential guide to creating a top-notch design system with Material UI

Our company is currently focusing on developing our design system as a package that can be easily installed in multiple projects. While the process of building the package is successful, we are facing an issue once it is installed and something is imported ...

Does anyone know of a JavaScript function that works similarly to clientX and clientY but for tooltips when the mouse moves?

When using plain JavaScript to create a function that moves a tooltip on mouse move, the function works the first time with clientX and clientY, but fails to work when repeated. What could be causing this issue with clientX and clientY? Any suggestions on ...

Tips for eliminating duplicate values from an array

In my NodeJS code, I am currently comparing values in an array. The issue at hand is: I start with an empty array: var items = []; then proceed to insert some values into it: items[0] = {a:1, b:222}; items[1] = {a:1, b:333}; items[2] = {a:1, b:222}; ...

At what point in the lifecycle of my component am I able to begin using this.$refs?

Exploring ways to integrate HTML5 audio events while initializing a Vue.js component that consists of a single file: <template> <audio ref="player" v-bind:src="activeStationUrl" v-if="activeStationUrl" controls autoplay></audio> < ...

What is the best method to transform a Dictionary of integers and longs into a string array or list?

Can someone assist me with converting a Dictionary into a string array or list? The desired format of the string array should be in the form of "ID, PTS", where ID is an integer and PTS is a long. Any help would be greatly appreciated! Thanks, ~Nikku. ...

Retrieve elements from a numpy array using a separate array containing only 0 and 1 values as indices

If you have an index array called idx that contains only 0s and 1s where 1s represent the sample indices of interest, along with a sample array called A (A.shape[0] = idx.shape[0]), the goal is to extract a subset of samples based on the index vector. In ...

What is the best way to design versatile div containers that combine the float property with fluid dimensions?

I am attempting to achieve a specific layout where the width of the content_container extends up to the right side of the screen and dynamically adjusts based on whether the expandable pane is collapsed or expanded. Applying width: 100% to .content_contain ...

Unable to send a PHP array to jQuery

Struggling to transfer PHP-encoded array to JavaScript. homepage.php echo '<script src="script.js"></script>'; $a=array(1,2,3,4,5); echo json_encode($a); ?> script.js: $.ajax({ method: 'GET', url: 'index ...

What causes an error when trying to access with the member access operator?

When dealing with object properties in the code snippet below, an error is thrown when trying to access the object using the Member Access. Why does this happen? var d = {a: 10, b: 20, c:30}; var keys = Object.getOwnPropertyNames(d); ...

Tips for handling Vue/Axios JSON payload sent data in Yii2

After spending some time trying to figure it out, I finally realized the solution, which was a bit obvious. I am sharing my answer here so that others can benefit from it and also to see if there is a more efficient way to handle this issue. The problem I ...

ReactForms Deprication for NgModel

According to Angular, certain directives and features are considered deprecated and could potentially be removed in upcoming versions. In a hypothetical scenario, let's say I am using NgModel with reactive forms, which Angular has marked as deprecate ...

HTML steps for smooth scrolling to the top and bottom of a list

My HTML contains a vertical list with top and bottom arrows positioned nearby. I am looking to implement a function where clicking on the top arrow will move the list up gradually, and clicking on the bottom arrow will move the list down step by step. Belo ...

Modify keys in an array created dynamically using PHP

I'm working with a PHP array where each key starts with the character "@a". How can I go about removing this symbol from all keys? The challenge is that I don't know for sure what specific keys will be present, but I definitely need to get rid of ...

Querying a document by its Id using only JSON in MongoDB

I am trying to query a document in Mongodb (2.6.1) using pure JSON without using ObjectIds. According to the mongodb extended json documentation, I expected the code db.collection.findOne({"_id": {"$oid": "51b6eab8cd794eb62bb3e131"}}) to work but it is th ...

Transforming a redux form onSubmit function into a promise-based structure

One of my goals is to promisify the onSubmit handling in my submitForm for redux form. You can find a similar example here. submitForm = () => { return this.props.submituserForm() .then(() => { console.log('test') }) ...