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

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

Showing data in json format using Angular

I have designed a data table that showcases a list of individuals along with their information. However, when I click on the datatable, it keeps opening a chat box displaying the details of the last person clicked, overriding all other chat boxes. 1. Is t ...

"Learn how to transfer a selected value from a parent ASP.NET dropdownlist to a textbox in a popup window using JavaScript

I'm struggling to pass the value from a dropdown list in the parent ASPX form to a textbox in the child ASPX form. Parent JavaScript: The first script is used to open the popup window <script type="text/javascript"> var popup; ...

Leveraging the power of React in conjunction with an HTML template

After purchasing an HTML template from theme forest, I am now looking to incorporate React into it. While I find implementing Angular easy, I would like to expand my skills and learn how to use React with this template. Can anyone provide guidance on how ...

The function Mediarecorder.start() is experiencing issues on Firefox for Android and is not functioning

Recently, I've been facing a peculiar issue while developing a web application. The purpose of this app is to capture about 10 seconds of video intermittently from the device webcam and then upload it to a server. For this functionality, I utilized th ...

Avoiding Vue Select from automatically highlighting the initial option: tips and tricks

Currently utilizing Vue Select as a typeahead feature that communicates with the server via AJAX. By default, the first option from the server response is highlighted like this: https://i.stack.imgur.com/jL6s0.png However, I prefer it to function simila ...

I am facing a dilemma with Expressjs when it comes to managing numerous users simultaneously

I'm grappling with a conceptual dilemma as I delve into the world of building an expressjs app. My goal is to create a system where each user, upon starting the app, has their own temporary folder for storing various files. Despite my lack of experien ...

Add data to a nested array with Vuex

Currently, I am facing a challenge with adding an object to a nested array in Vue using store / vuex. While I have successfully updated the main comments array with a mutation, I am struggling to identify the specific main comment to which the new reply ob ...

Encountering an unexpected token error while using JSON.parse()

When attempting to parse this JSON string, I encounter an error indicating an unexpected token $scope.feeds = JSON.parse('[{"id":"212216417436_10152811286407437","from":{ "category":"Movie","name":"The Lord of the Rings Trilogy","id":"212216417436"}, ...

Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data function post_data_async_globalEval(post_url, post_data, globaleval) { $.ajax({ type: 'POST', url: post_url, data: post_data, dataType: 'html', async: true, ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

What is the correct way to deserialize this object properly?

I am facing a challenge with deserializing data from an API that provides a list of company symbols along with their respective properties. I need guidance on how to effectively deserialize this information. { "A": { "advanced-stats": { ...

Mapping Store Fields to JSON Properties in ExtJS: A Complete Guide

I am working with a JSON data object that includes exchange rates information: { "disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, ...

Execute Function after Gridview Sorting

While working on a gridview within an update panel, I encountered a scenario where the gridview successfully resorts itself upon clicking on the column header. However, post-sorting, I wish to execute a JavaScript function named MyScript. Any suggestions ...

What steps can be taken to resolve an error encountered when attempting a dynamic data POST request from the body

Whenever I attempt the post method to fetch data on Postman and store it in a local MongoDB database, I encounter an error. The error message indicates a bad request with a status code of 400. *The following is app.js: var express = require('express& ...

Submitting data using AJAX yields results, but the contact form remains untouched

I have created an online quiz using jQuery. My goal is to send the results, along with the user's contact information, to the moderator once they submit it. I have managed to send the result information successfully. However, I am facing an issue whe ...

Elegant Box 2 - Ascending to the top when clicked

I am excited to share that I am using FancyBox for the first time in my project. This time, I decided to separate the image from the link for a unique user experience. The hover effect works perfectly fine - the issue arises when the link is clicked and th ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

Sending data with the request body using Express and Passport

I've created a login application using Express and Passport, but I'm having trouble directing the user to their specific user profile page. The goal is for users to fill out an HTML form and then be redirected to their own profile page (which dif ...

Finding the median value within a collection of objects

I am working with an array of objects containing book details: const booksData = [{"author":"john","readingTime":12123}, {"author":"romero","readingTime":908}, ...