Multiply a scalar by each element in an object's array

I am trying to work with an array of objects where each object contains some arrays. I want to easily access the values within these arrays, such as multiplying them by a constant.

It seems like using forEach() might be the best approach. Here is how I attempted it:

myArray = [{
    income: [1, 2, 3],
    outcome: [2, 3]
  },
  {
    income: [1, 9, 8, 5],
    outcome: [1, 3, 7]
  },
  {
    income: [7, 2, 8],
    outcome: [2, 6, 10]
  },
];

const myValue = 2;
myArray.forEach(ob => ob.income = ob.income * myValue, ob.outcome = ob.outcome * myValue);

Based on this operation, the expected result should look like this:

myArray = [
  {income: [2, 4, 6], outcome: [4, 6]},
  {income: [2, 18, 16, 10], outcome: [2, 6, 14]},
  {income: [14, 4, 16], outcome: [4, 12, 20]},
];

Answer №1

To iterate over all objects, you can simply utilize the forEach() method and then obtain the desired result by using Array.map().

let myArray = [
            {income: [1, 2, 3], outcome: [2, 3]},
            {income: [1, 9, 8, 5], outcome: [1, 3, 7]},
            {income: [7, 2, 8], outcome: [2, 6, 10]},
];

const multiplyBy = 2;

myArray.forEach((obj)=> {
  obj.income = obj.income.map((a) => a * multiplyBy);
  obj.outcome = obj.outcome.map((a) => a * multiplyBy);
});

console.log(myArray);

Answer №2

One approach is to transform all properties and assign new properties to fresh objects.

var array = [{ income: [1, 2, 3], outcome: [2, 3] }, { income: [1, 9, 8, 5], outcome: [1, 3, 7] }, { income: [7, 2, 8], outcome: [2, 6, 10] }],
    factor = 2,
    result = array.map(o => 
        Object.assign(...Object.entries(o).map(([k, v]) =>
            ({ [k]: v.map(f => f * factor) }))));

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

Modifying the original array

var array = [{ income: [1, 2, 3], outcome: [2, 3] }, { income: [1, 9, 8, 5], outcome: [1, 3, 7] }, { income: [7, 2, 8], outcome: [2, 6, 10] }],
    factor = 2;

array.forEach(o => 
    Object
        .entries(o)
        .forEach(([k, v]) => o[k] = v.map(f => f * factor))
);

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

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

A function that creates a new object with identical keys as the original input object

I am working on creating a function fn() that has the following specifications: It takes a single argument x which is an object with optional keys "a" and "b" (each field may be numeric for simplicity) The function should return a new object with the same ...

Having trouble with Next.js and Next-auth? When I make an HTTP request in getServerSideProps, getSession is returning null in my secured API Route

I am currently working on securing an API Route that is being called from both the Client and Server-side on different pages. When accessing the test page, it returns a 401 error. However, when accessing the test2 page, the content is retrieved successfu ...

Guide to converting a json file into a JsonArray object using C#

Can anyone help with parsing a JSON file into a JsonArray object using C#? [ { "id": 1, "first_name": "LAkshan", "last_name": "Parcell", }, { "id": 2, "first_nam ...

Using a Typescript variable prior to its assignment

I encountered an issue in my Typescript / ReactJS project displaying the error message Variable 'myVar' is used before being assigned. TS2454 This problem arises with my TS version 4.2.3, appearing both in my IDE and during code execution. Inte ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Expression enclosed in double quotes within a JavaScript string

Our company has encountered an issue with an FTL that involves a link with JavaScript functionality. The problem arises when the value contains an apostrophe, causing the link to break. To address this, we utilized the js_string method to solve the issue. ...

Incorporating a favicon into a Next.js React project

I'm currently working on integrating a favicon into a Next.js project that was generated using create-next-app. The favicon.png file is stored in the public folder, and I followed the instructions for serving static files outlined here. In my Layout ...

Ways to activate script following an ajax request

I'm currently using a form that utilizes an event listener to detect when a button is clicked and then transitions the form to the next fieldset. I need to perform an ajax call and once it's finished, trigger this call. However, I'm having ...

Methods for transferring data from child to parent in TSX components

There is a value in the parent component value={this.onUpdate(index)} and the onUpdate function manipulates the value and index In the child component, there is an input field with onChange={this.handleText(index)} This calls a method that tries to p ...

Processing the file to convert it into an array of integers

Currently, I am tackling HEVC specifically X265, and my focus is on inputting the QP array with values read from a file. It's important to note that these values range from 0 to 100. To test this process, I have set up a test file where I've inc ...

Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so: var getSelectedText = function() { var text = ""; if (typeof window.getSelection !== "un ...

Having trouble getting card animations to slide down using React Spring

I am currently learning React and attempting to create a slide-down animation for my div element using react-spring. However, I am facing an issue where the slide-down effect is not functioning as expected even though I followed a tutorial for implementati ...

Guide on using Ajax to transmit data to Struts2 action class

In my Struts2 web application, I have the following files: member.jsp: <script type="text/javascript"> String str1 = "aaa"; String str2 = "bbb"; xmlhttp.open("GET", "http://localhost:8080/project/editprofile.action", true); xml ...

Combining Arrays with Identical IDs into a Single Object

When two objects in the data array share the same id, only the first one will be chosen and the rest will be discarded. It is important that multiple assets with the same id are grouped together in one object. const myMap = cardDetails.map((card) => { ...

Leveraging Javascript/Jquery for numbering items in a list

This is a snippet of HTML code that I am working with: <ul> <li data-slide-to="0" data-target="#myCarousel" class="appendLi"></li> <li data-slide-to="0" data-target="#myCarousel" class="appendLi"></li> <li data ...

What is the best MySQL data type for storing JavaScript code with PHP?

I am creating a platform that resembles jsfiddle, allowing users to store their JavaScript codes and retrieve them in an organized manner. I am unsure about which data type would be most suitable for saving the codes, or if storing them in text files wou ...

Is the focus styling malfunctioning within a React component?

Issue: I'm facing a challenge with my custom search box in a React application. Despite my styling efforts, I can't seem to get the desired outline effect when someone types in the textbox. <div className="search-box"> <Row> & ...

Learn the process of updating an Array with a list of values based on checkbox selection and dynamic filtering using AngularJS

$scope.selectObjectType = function () { $scope.selected = []; // reset previous selection $scope.model.allItemsSelected = true; // all are selected by default unless... // If any object type is not checked, then uncheck the "allItemsSelected" ...

Enhance User Experience by Updating Status on Checkbox Selection in PHP

I am working with a datatable and I have created a table using datatables. How can I change the status field when a checkbox is clicked? The default status is 'before', but when the checkbox is clicked, it should update to 'after' in th ...

Top method for discovering a corresponding value within an array by comparing it with another collection of values through Angular

Received the array below from a service which contains roles of a logged in user: roles = ['MM_VIEW', EM_VIEW] I have a specific requirement where I need to check if the user has any of these roles - MM_VIEW, MM_EDIT, MM_DELETE. Based on this, I ...