Navigating an array and organizing items based on matching properties

When I receive an array that looks like this:

errors = [
    {
        "row": 1,
        "key": "volume",
        "errorType": "Data type",
        "expectedType": "number",
        "receivedType": "string"
    },
    {
        "row": 1,
        "key": "units",
        "errorType": "Required data",
        "expectedType": "string"
    },
    {
        "row": 3,
        "key": "year",
        "errorType": "Incorrect data type",
        "expectedType": "number",
        "receivedType": "string"
    },
    {
        "row": 3,
        "key": "make",
        "errorType": "Required data",
        "expectedType": "string"
    }
]

My goal is to transform it into an array of objects structured like this:

const errorGrouped = [
  {
  row:1,
  data:[
    {
      "key":"volume",
      "errorType": "Data type",
      "expectedType": "number",
      "receivedType": "string"
    },
    {
      "key": "units",
      "errorType": "Required data",
      "expectedType": "string"
    }
  ]
  },
  {
  row:3,
  data:[
    {
      "key": "year",
      "errorType": "Incorrect data type",
      "expectedType": "number",
      "receivedType": "string"
    },
    {
      "key": "make",
      "errorType": "Required data",
      "expectedType": "string"
    }
  ]
  }
]

I have tried mapping through each object and destructuring them into the desired format of [{row:.., data:[...]}], but I'm struggling to group them efficiently. I believe there might be a better solution for this. Any help would be greatly appreciated. Thank you.

Answer â„–1

To efficiently achieve this task within a single loop, utilize a hash (JS Object) to store the row index in the array for easy access.

  • The hash will eliminate the need to repeatedly look up the row index.
  • Once you have the index, simply access the specified array position to insert the data.

const errors = [
    {
        "row": 1,
        "key": "volume",
        "errorType": "Data type",
        "expectedType": "number",
        "receivedType": "string"
    },
    {
        "row": 1,
        "key": "units",
        "errorType": "Required data",
        "expectedType": "string"
    },
    {
        "row": 3,
        "key": "year",
        "errorType": "Incorrect data type",
        "expectedType": "number",
        "receivedType": "string"
    },
    {
        "row": 3,
        "key": "make",
        "errorType": "Required data",
        "expectedType": "string"
    }
];

const rowMapIndex = {};
const output = [];

for (let rowObj of errors) {
    const { row: rowID, ...restObj } = rowObj;

    let addAt = output.length;
    if (rowID in rowMapIndex)  {
        addAt = rowMapIndex[rowID];
    } else {
        rowMapIndex[rowID] = output.length;
        output.push({ row: rowID, data: [] });
    }
    output[addAt].data.push(restObj)
};

console.log(output);

Answer â„–2

To efficiently group errors by row in JavaScript, utilize the reduce method.

const errorGrouped = errors.reduce((accumulatorList, error) => {
    const group = accumulatorList.find(g => g.row === error.row);    
    if (group) {
        // Add error to existing group
        group.data.push(error);
    } else {
        // Create a new group for the row
        accumulatorList.push({ row: error.row, data: [error] });
    }
    // Remove row attribute from the error object
    delete error.row;
    
    return accumulatorList;
}, []);

console.log(errorGrouped);

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

Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level. Array: options: [ {name: 'Ð’Ñ‹Ñ…Ð ...

Oops! There seems to be a problem with your AngularJS/JavaScript code. The error message is "Uncaught ReferenceError:

As I venture into the world of AngularJS and JavaScript, I am working on creating a 'blog' using these technologies. Here is my HTML view code- <div ng-controller="Controller1"> <form ng-submit="sub()" role="form"> Title: <textar ...

An issue occurred while attempting to read words from JSON file

My current issue involves loading words from JSON into my webpage. The images are functioning properly, thankfully. I have already successfully loaded the necessary images through JSON onto my webpage. However, I am still in need of loading words through ...

What is the best way to consolidate all app dependencies into a single package?

Recently, I came across Cory House's ingenious solution for package management in Node.js during his informative presentation. In their project portfolio, House's team maintains a package called Fusion, which serves as a central repository for a ...

Unable to modify the selector to "Remove preview files" on click in PHP and JavaScript

During the process of uploading multiple files (using <input type="file" multiple/>) with preview image file and successfully removing the image preview and file data, I encountered a problem. The issue arises when attempting to change the selector ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Encountering a 500 error within a Passport JS and React application

I'm currently developing a chat application using React, and I've hit a roadblock while trying to authenticate users. The axios post request is throwing a 500 error that seems to be elusive. Even when the correct credentials are entered for a use ...

Setting a consistent theme or style for all HTML/React tags using a selector inside a specific component

Here's a simplified example of what I'm trying to do: I'm using Material UI Styles for styling my components. I want to style all the <Link> tags in my component. For instance: const useStyles = makeStyles(theme => ({ menuLink: ...

The type of 'data' is assumed to be 'any[]' without being explicitly stated

I am encountering several type errors in the function below, and as a newcomer to Typescript, I'm unsure about how to fix them. private fetchFromUrl = () => { var data = [] fetch(`${process.env.PUBLIC_URL}/tempData/monthly.csv`) .t ...

Error in scrolling previews detected in Jssor horizontal template maker

I've been working with Jssor Slider Maker and I'm using the vertical preview template that features two columns on the left side and a maximized image on the right side. After pulling the code from the developers pack, it includes scripts, CSS an ...

The initial rendering of the NextJs 13 application is experiencing significant sluggishness when deployed on an EC2

After deploying my NextJS 13.4 app on an AWS EC2 instance with 2 GB of RAM, I noticed that the initial load time is quite slow, taking around 20 seconds to load for the first time. The development mode in NextJS builds and displays the result, which may co ...

The optimal method for designing a select menu to ensure it works smoothly on various web browsers

Recently, I encountered an issue with customizing a select menu using CSS and jQuery. After some work, I was able to achieve a result that I am quite pleased with: So far, the styling works perfectly in Mozilla, Opera, Chrome, and IE7+. Below is the curr ...

What is the best way to display an image right in the middle of the header?

My project consists of three main files - an HTML, a CSS, and a JS file. I have developed the HTML using the Bootstrap 5.1.3 framework. The issue I am facing pertains to the alignment of the clothing brand logo within the header section. Despite multiple ...

Guide to utilizing Terser in conjunction with webpack

I am currently using Webpack 6.10.2 in combination with Vue 3.9.3. I encountered an issue with Uglify.js when running npm run build due to its inability to handle ES6 code. To work around this problem, I followed the recommendation of removing Uglify fro ...

Retrieve all values of a specific enum type in TypeScript

When working with Typescript, I am looking to retrieve all values of an enum type and store them in an array. In C#, a similar method would look like this: public static TEnum[] GetValues<TEnum>() where TEnum : Enum { return Enum.GetValues(typeof ...

The request does not include the cookies

My ReactJS client sends a cookie using this NodeJS code snippet: res.cookie("token", jwtCreation, { maxAge: 24 * 60 * 60 * 1000, // Milliseconds (24 hours) sameSite: 'None', // Cross-site requests allowed for modern browser ...

When I navigate to the URL using a router-link, the v-for in my Vue.js component renders properly. However, if I manually type the URL or refresh the page, the v-for fails to render

Whenever I navigate to a specific URL that showcases icons of characters from a game, everything functions as expected and the icons are displayed. However, upon refreshing the page, the icons vanish. If I manually enter www.example.com/champions, the ico ...

Ways to eliminate excess space in a string using Robot Framework

My Variable : 54, 22 What I desire : 54,22 I attempted the following methods: Executing Javascript code var a = 54, 22;var x = a.split(' ').join('');return x and Executing Javascript code var a = 54, 22;var x = a.replace(/&bso ...

Exploring solutions to this problem with the use of classes, vectors, and other related methods

Recently, I began learning OOP C++ from scratch, despite having prior programming experience. The current focus is on classes, objects, and constructors. While I grasped the concept to some extent, I encountered a specific task that is proving challenging. ...

Access the array value in AngularJS based on a different property array

Here are my Arrays: var FirstArr=[ { "id":"123", "aboutUS":"Demo About Us" }, { "id":"234", "tutorial":"Demo Tutorial" } ...