Modifying reduce callback to prevent accumulator reassignment

Here is a function I wrote:

 type Data = {
    x?: number[],
    y?: number[],
    z?: number[],
  };

  const sampleData = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

  const updatedData = sampleData.reduce((accumulator, element) => {
    Object.entries(element!).forEach(([key, value]) => {
      accumulator = { ...accumulator, [key]: [...(accumulator[key as keyof Data] || []), value] };
    });

    return accumulator;
  }, {} as Data);

Although this code accomplishes its purpose, it triggers an eslint error stating no-param-reassign.

I am aware that I can disable the rule, but I'm curious if there's a more optimal way to structure this reduce callback without reassigning accumulator.

Answer №1

To directly assign to acc[k], you can use the following code:

const data = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

const formattedData = data.reduce((acc, el) => {
  Object.entries(el).forEach(([k, v]) => {
    acc[k] = (acc[k] || []).concat(v);
  });
  return acc;
}, {});

console.log(formattedData);

For a more efficient approach with fewer allocations and copies, you can use this optimized code:

const data = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

const formattedData = data.reduce((acc, el) => {
  Object.entries(el).forEach(([k, v]) => {
    if (!acc[k]) {
      acc[k] = [];
    }
    acc[k].push(v);
  });
  return acc;
}, {});

console.log(formattedData);

Answer №2

When you see the 'no-param-reassign' warning, it indicates that you have altered the function parameters within the function itself. To address this warning, consider implementing a solution like the following:

type ChartData = {
  x?: number[],
  y?: number[],
  z?: number[],
};

const data = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

const formattedData = data.reduce((acc, el) => {
  let newAcc = { ...acc };
  Object.entries(el!).forEach(([k, v]) => {
    newAcc = { ...newAcc , [k]: [...(newAcc [k as keyof ChartData] || []), v] };
  });

  return newAcc ;
}, {} as ChartData);

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 there a way to use Javascript to verify if a window is fully open?

Is there a way to detect the complete opening of a window using JavaScript? // code1 is not functioning $(window).resize(function() { ... }); // code2 is not working window.onresize = function(event) { ... } I am ...

Can you explain the role of the faceVertexUV array within the three.js Geometry class?

Currently, I am utilizing three.js to create curved shapes using parametric functions. Within the THREE.js javascript file, there is a function called THREE.ParametricGeometry that continuously adds 2D vectors to the faceVertexUvs array. I am curious abo ...

Utilizing PHP and JavaScript to Transmit Multiple MySQL Result Sets from a Popup Window

I am attempting to transfer multiple sets of MySQL data through JavaScript from a popup page to the main page. Here is my progress so far: In my popup.php page: $sql = mysql_query("SELECT * from item where category like '$catego ...

Re-rendering multiple components with the new `use` feature in React version 18.3.0

When trying to fetch and use data using React 18.3.0, I encountered an issue with multiple re-rendering. react: 18.3.0-canary-3ff846d10-20230724 next: 13.4.12 The code for SuspenseTest component is causing multiple console outputs (about 5 to 8 times) be ...

The error message "TypeError: Cannot access the tapAsync property because it is undefined"

"webpack": "^7.89.0", "webpack-cli": "^6.2.8", After updating webpack to the versions above, I encountered this error: clean-webpack-plugin: /home/itrus/react/living_goods/build has been removed. TypeError: Cannot r ...

Switching between nested lists with a button: A simple guide

I have successfully created a nested list with buttons added to each parent <li> element. Here is how the list is structured: $("#pr1").append("<button id='bnt-cat13' class='buttons-filter'>expnd1</button>"); $("#pr ...

Javascript error when attempting to add leading zeros

Is there a way to utilize JavaScript or JQuery in order to prepend a zero to this script? for (im=1;im<=31;im++){ days[im]=everyDay[im]; } ...

Does MongoDB have a method to identify the presence of an element within an array?

I am currently working on a query where I need to ensure that a specific string does not appear in an array. The schema I am using looks like this: _id: { type: String, required: true }, ... meta: { user_likes: { ...

Simultaneously removing and inserting components with Meteor.js

I have a straightforward set of items that is displayed like this {{#each items}} {{> item}} {{/each}} My code defines that only the three most recent items are shown return Items.find({}, {sort: {timestamp: -1}, limit: 3}) Whenever a new item i ...

Using UI-Router in AngularJS to redirect a state to its default substate

I am currently developing a tab-based page that displays data using UI-Router in AngularJs to manage states. My main goal is to have one default tab open when the page loads. Each tab contains sub tabs, and I want a default sub tab to be open whenever a t ...

Utilize JavaScript to substitute font family with a designated class name

After discovering a code snippet that can change font family based on ID, I am interested in implementing it on my website but with a twist - using classes instead of IDs. <!DOCTYPE html> <html> <body> <div class="myP">This is a ...

JSX conditionally rendering with an inline question: <option disabled value="">Select an option</option>

Yes, I can confirm that the inline is functioning properly because in the Convert HK to Passive Segment paragraph at the top I am seeing the expected output. What I am aiming for is to display a "Choose a hotel" message when there are multiple hotels in th ...

Incorporate the ability to display a shape on a map when hovering over a table element, without the need to manually code a JavaScript function for every instance

I came across a script online that allows me to hover over text and have a shape appear on an imagemap. It's functional, but only works for a single instance. Is there a way to implement a JavaScript that handles individual instances so I don't h ...

Finding it difficult to grasp the concept of asynchronous functions in NodeJS

I've been grappling with this NodeJS challenge for a good 6 hours already. Currently, I'm working with NodeJS along with Express and MongoDB. In my database, there are two collections - Listings and Categories. Each listing is linked to a categ ...

The element is inferred to have an 'any' type due to the fact that a 'string' type expression cannot be used to access elements in the type '{ Categories: Element; Admin: Element; }'

As someone who is new to TypeScript, I am trying to understand why I am encountering a type error in the code below (simplified): "use client"; import { ArrowDownWideNarrow, Settings } from "lucide-react"; interface LinkItemProps { ...

Using Angular to make an API call within a JavaScript function

I am facing an issue when trying to call an API in a JavaScript function as shown below. The injected services (subService) and defined variables (formData) are not recognized in the JavaScript function, resulting in an error of undefined addSub. How can I ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

nw.js sending a multipart/form-data request

I am looking to send POST data to a server from nw.js. The data consists of simple name-value pairs and one file, meaning that the request type will be multipart/form-data. All the data needs to be sent in one single request. To do this, I have been using ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Generate a 2D array in C programming language

Trying to develop a program that can take input for 10 student names, but struggling with how to store them. The code snippet below is just a rough draft showcasing my approach to handling the input of names. Limited to using C language only. Desired outp ...