Changing a single array into a series of arrays

I'm attempting to reverse the flattening process of an array.

The JSON array I have as input contains 4 elements:

[
  {
    "nestedObj": {
      "id":12
    }
  },
  {
    "nestedObj": {
      "id":555
    }
  },
  {
    "nestedObj": {
      "id":555
    }
  },
  {
    "nestedObj" :{
      "id":771
    }
  }
]

I aim to convert it into an array of arrays, with each sub-array containing elements grouped by their nestedObj.id.

The initial JSON is assumed to be sorted by nestedObj.id.

In the example above, since the id of nestedObj for the 2nd and 3rd elements are the same (555), they will be grouped together in one sub-array.

The resulting array will consist of only 3 sub-array elements:

[
  [{
    "nestedObj": {
      "id":12
    }
  }],
  [{
    "nestedObj": {
      "id":555
    }
  },
  {
    "nestedObj": {
      "id":555
    }
  }],
  [{
    "nestedObj" :{
      "id":771
    }
  }]
]

This code provides the desired output:

const data = [ /* ...the above input data... */ ];
let result = [];
let prevId = null;
for (let elem of data) {
  let currId = elem.nestedObj.id;
  if (currId === prevId) {
    result[result.length - 1].push({...elem});
  } else {
    result.push([{...elem}]);
  }
  prevId = currId;
}

However, the code is quite verbose. It lacks the elegance of modern JavaScript techniques like 'reduce' or other functional programming approaches. Can anyone suggest a sleeker rewrite?

Answer №1

Simply group together the elements.

let array = [{ nestedObj: { id: 12 } }, { nestedObj: { id: 555 } }, { nestedObj: { id: 555 } }, { nestedObj: { id: 771 } }],
    result = Object.values(array.reduce((r, o) => {
        (r[o.nestedObj.id] = r[o.nestedObj.id] || []).push(o);
        return r;
    }, {}));

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

Answer №2

To group by ID, you can utilize the reduce function, extract the grouped values with Object.values, and then use map to construct the desired output.

Assuming there's a single attribute named nestedObj

let array = [{ nestedObj: { id: 12 } }, { nestedObj: { id: 555 } }, { nestedObj: { id: 555 } }, { nestedObj: { id: 771 } }],
    finalResult = Object.values(array.reduce((accumulator, {nestedObj: {id}}) => {
      (accumulator[id] || (accumulator[id] = [])).push(id);
      return accumulator;
    }, {})).map(subresult => subresult.map(id => ({nestedObj: {id}})));

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

Answer №3

Utilize a Map to categorize items by their shared id and then extract the final values from the Map

const data = [{ nestedObj: { id: 12 } }, { nestedObj: { id: 555 } }, { nestedObj: { id: 555 } }, { nestedObj: { id: 771 } }]

const map = new Map;

data.forEach(o => {
  const {nestedObj:{id}} = o;
  map.has(id) ? map.get(id).push(o) : map.set(id,[o]);
});

console.log([...map.values()])

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

What could be causing my JavaScript code to fail to add data when the submit button is

I'm currently working on a Hot and Cold App using JS and jQuery. The problem I'm facing is that upon form submission, the user input inserts a number, and the game should provide feedback by telling them if it's hot, cold, hotter, or colder ...

When attempting to capture an element screenshot as PNG, a TypeError occurs indicating that the 'bytes' object is not callable

Can someone please help me figure out how to save a screenshot of a specific element in Selenium using Python3? Here is the code I am trying: from selenium import webdriver import pyautogui as pog import time options = webdriver.ChromeOptions() options ...

Changing the visual appearance of an alert in JavaScript and HTML

My knowledge in JavaScript is limited, but I have a script that retrieves a query from a Python service to a Mongodb database. The query is returned in the following format: [{CHAIN: "STREET ELM, ELMER", CODE: "1234"}, {CHAIN: "STREET LM, LMAO", CODE: ...

Is it possible to combine asynchronous and synchronous functions in the same code?

I've recently started experimenting with Node.js and I'm running into issues with asynchronous functions. While I was able to create a small game, the only way I could successfully integrate asynchronous functions with synchronous functions was b ...

Passing props to component elements through slots in Vue.js

Trying to pass props from a component element that includes a slot PatientBooking.vue <user-profile :titlename="BOOKINGDETAIL"> <div class="block"> <div>Ereferral: 84884jjd</div> <div>Gender: Mal ...

Issue with $.ajax({}) causing Express Session to fail saving

I'm facing an issue where I am trying to store data in an Express session, but it seems that Express is treating each AJAX request as a new session and not saving my data consistently. Here's the client-side code: $.ajax({ url: '/orders& ...

What is the most effective way to retrieve the count of users who have logged in within the past three months by utilizing Jquery

I am seeking to retrieve the count of users who have logged in the last three months utilizing a JSON API and Jquery. This is my current progress: $.getJSON('users.json', function(data) { var numberOfUserLogged = 0; var d1 = ...

Checking the validity of subdomain names using JavaScript/jQuery

For users signing up, my form allows them to choose a subdomain for their account. The valid characters allowed in the subdomain are letters, numbers, and dashes. Spaces and most special characters should be filtered out. http://_________.ourapp.com To r ...

Getting the desired value from a CreatableSelect in React can be achieved by following these steps:

I have a form that includes a React library component called React Select. I'm struggling to retrieve the target value of this input field. Here's my code snippet: # CreatableSelect tag <CreatableSelect className={Astyle.selectInput} i ...

Using JavaScript to fetch elements by their ID along with a button

UPDATE: I have corrected the semi-colons, case sensitivity, and brackets in the code. It functions properly if I eliminate the functions after buttonPARTICULAR! Why is that? UPDATE: Issue resolved. My mistake. Apologies!!! :-Z When I simplify it like thi ...

Struggling to design a button that can delete tasks from the list, but encountering issues with the filter function

Although I am able to push values, I seem to be struggling with the filtering process. Can anyone provide guidance on whether I am using the filter method incorrectly or if there is another issue at play? import { useState } from 'react'; const ...

JavaScript code not functioning on WordPress website (no impact)

I've encountered a strange problem. Here is the code snippet: (function($){ $("#maps1").hover( function(){$("#kontakt_os_1").hide();} ); $("#maps2").hover( function(){$("#kontakt_os_2").hide();} ); $("#maps3").hover( ...

Streaming videos using Flask with a custom template

After successfully implementing the DWA path planning algorithm in C with Python bindings, I have decided to create a web application demo. The concept involves a "robot" following the mouse using DWA, while allowing users to draw walls for objects. My ini ...

Could you please ensure that the animation activates upon hovering over the "a" element?

Utilizing bootstrap, I have created the following code. I am looking to add functionality that triggers an animation upon mouseover of an img or a element, and stops the animation upon mouseleave. .progress-bar { animation: pr 2s infinite; } @keyfr ...

What is the reason behind the widespread adoption of Node.js and NPM for the compilation of JavaScript libraries by

The widespread adoption of Node.js and NPM in the JavaScript community has left me perplexed. Why must we rely on such drastic measures? What issues are these tools aiming to resolve for us? [Update] I feel like my original question missed the mark. Fra ...

When using React, appending a React Link tag to an existing list item may result in the addition of two objects instead of the desired

Trying to create a loop that checks if an object's date matches with a date on a calendar. If it does, I want to add a React Link tag to the respective li element. The loop logic works well, but the issue is when appending the Link tag using createTex ...

Is there a way to selectively transfer attributes and behaviors from an interface to a fresh object in typescript?

Is there a way in javascript to selectively copy properties from one object to another? I am familiar with using Object.assign() for this purpose. Specifically, I am looking to extract only the properties defined within the following interface: export in ...

Caution: It is not possible to make changes to a component (`App`) during the rendering of another component (`History

I am currently in the process of creating a tic tac toe game, but I'm encountering an error that is preventing me from updating the history. Despite following a tutorial on skillshare.com and mirroring the steps exactly, the error persists. I must men ...

fullpage.js: the content exceeds the height limit

I am currently working on customizing the jquery script fullpage.js for a website built on the French CMS "SPIP" (). This script is used to create a one-page website with both horizontal and vertical navigation. However, I have encountered an issue with ...

Encountering a pair of errors while working with Node.js and Express

(Apologies for the vague title) I have been developing a project using Firebase and Express, but I am encountering some issues. src/index.js import { initializeApp } from "firebase/app"; import { doc, getFirestore } from "firebase/firesto ...