Calculate the difference in properties between consecutive objects in an array

I have a collection of objects like this:

 "stock": [
    {
        "Quantity": -36,
        "Price": 74.55,
        "Consideration": 2683.8,
        "Direction": "SELL"
    },
    {
        "Quantity": -50,
        "Price": 74.14,
        "Consideration": 3707,
        "Direction": "SELL"
    },
    {
        "Quantity": 12,
        "Price": 77.15,
        "Consideration": -925.8,
        "Direction": "BUY"
    },
    {
        "Quantity": 15,
        "Price": 76.4,
        "Consideration": -1146,
        "Direction": "BUY"
    },
    {
        "Quantity": 19,
        "Price": 75.8,
        "Consideration": -1440.2,
        "Direction": "BUY"
    },
    {
        "Quantity": 20,
        "Price": 82.44,
        "Consideration": -1648.8,
        "Direction": "BUY"
    },
    {
        "Quantity": 10,
        "Price": 82.08,
        "Consideration": -820.8,
        "Direction": "BUY"
    },
    {
        "Quantity": 10,
        "Price": 82.49,
        "Consideration": -824.9,
        "Direction": "BUY"
    }
]

I aim to deduct the PRICE attribute of each object from the previous one and include the result as profit in that preceding object...

So starting from the first object in the array, I will have;

74.55 - 74.14 and the outcome will be added to the second object as
profit: "result:

The only solution I can think of is this:


            let stockData = stock.map((stock) => {
            return {
                Quantity: stock.Quantity,
                Price: stock.Price,
                Consideration: stock.Consideration,
                Direction: stock.Direction,
            };
        });

        for (let i = 0; i < stockData.length; i++) {
            let profit = stockData[i].Price - stockData[i - 1].Price;
        }

        res.status(200).json({
            stock: stockData,
        });

However, when accessing stockData[i - 1].Price, I encounter the error "can not read property Price of undefined"

Answer №1

Need something similar to this:

const finalResult = stock.map((current, index) => (current.profit = current.Price - stock[index+1]?.Price || 0, current));

// Iterate over the stock array and assign the profit property of each element as the difference between it and the next element

Check it out in action:

const stock = [{
    "Quantity": -36,
    "Price": 74.55,
    "Consideration": 2683.8,
    "Direction": "SELL"
  },
  {
    "Quantity": -50,
    "Price": 74.14,
    "Consideration": 3707,
    "Direction": "SELL"
  },
  {
    "Quantity": 12,
    "Price": 77.15,
    "Consideration": -925.8,
    "Direction": "BUY"
  },
  {
    "Quantity": 15,
    "Price": 76.4,
    "Consideration": -1146,
    "Direction": "BUY"
  },
  {
    "Quantity": 19,
    "Price": 75.8,
    "Consideration": -1440.2,
    "Direction": "BUY"
  },
  {
    "Quantity": 20,
    "Price": 82.44,
    "Consideration": -1648.8,
    "Direction": "BUY"
  },
  {
    "Quantity": 10,
    "Price": 82.08,
    "Consideration": -820.8,
    "Direction": "BUY"
  },
  {
    "Quantity": 10,
    "Price": 82.49,
    "Consideration": -824.9,
    "Direction": "BUY"
  }
]
const finalResult = stock.map((current, index) => (current.profit = current.Price - stock[index+1]?.Price || 0, current));
console.log(finalResult)

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

Utilizing JSON in a data-attribute

Hey all! I am facing a challenge with extracting data from a JSON object stored in a data attribute. While I have managed to extract the string within the data attribute, I am struggling to access the object itself. Below is the code snippet: HTML <a ...

Retrieve the blob value from outside the canvas by using the ToBlob() function asynchronously

I have encountered an issue with the HTMLCanvas element where it returns a blob object outside of the async toBlob() function. Since this function does not return an output value, I have attempted to declare a variable outside and then access it through th ...

Alert users before visiting external websites

Is there a way to notify users about external pages without using popups like in the first example here: https://i.sstatic.net/5QJLu.png Instead of the unwanted code shown above, is there an alternative solution? Is there a different approach that can be ...

Guide to resetting a CSS animation with pure JavaScript

My flexbox contains 4 images, each triggering an animation on hover. However, the animation stops if I hover over the same image again. I have tried various JavaScript solutions found online to restart the animation, but none seem to be working for me. S ...

Newbie - Encountering a "NaN" Error While Implementing this While Loop

As someone diving into the world of Javascript, I've been immersing myself in Nodejs tutorials. One tutorial has me navigating through an array that always starts with two non-numeric elements followed by numbers, requiring me to utilize array[2] as a ...

Tips for organizing the output of wp_query

I'm looking to organize the results of my wp_query, wanting to arrange them by different parameters without needing to run the query again. Here is what I have so far: $the_query = new WP_Query( $args ); I’d like to sort $the_query; WP_Query gives ...

Convert form data into a JSON object using Vue.js

I'm attempting to generate a JSON object from the submitted form data. Fortunately, I've accomplished this using a variable. However, is there an alternative approach for creating a JSON object? Form <form @submit.prevent="submit"& ...

The JQuery clone method is failing to generate a new table row

I have a table with a button that is supposed to add a new row dynamically when clicked. However, the functionality is not working as expected. The HTML and JQuery code can be found in this JSFiddle link. Any suggestions on how to fix this issue would be ...

Engine for Creating Mobile Games

Have you ever had an idea for a multiplayer mobile game? I have one in mind. I was thinking of creating a browser game so that both IOS and Android users can enjoy playing it. However, there is something that worries me. If I develop the game mostly using ...

Automatically update and reload Express.js routes without the need to manually restart the server

I experimented with using express-livereload, but I found that it only reloaded view files. Do you think I should explore other tools, or is there a way to configure express-livereload to monitor my index.js file which hosts the server? I've come ac ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

Trouble retrieving an array within a nested immutable object

Can you do this? render() { var items = this.props.items.course_list; console.log(items); return ( <div> </div> ) } Outcome: https://i.sstatic.net/ugSsN.png Attempt to access course ...

"Looking to retrieve data from an array instead of an object in JavaScript? Here's how you can

There is a slight issue with my fetch method in grabbing data from this link . I am attempting to use the .map function on it but instead of functioning properly, I encounter an error that says Unhandled Rejection (TypeError): jedis.map is not a function. ...

Troubleshooting the canLoad problem caused by returning an observable with a 404 error

I have implemented a check to call an API in the canLoad event for a module in my Angular application. However, even if the API returns a 404 error in the network, my page continues to load. I want to change this behavior so that if a 404 error is encount ...

Is the `key` function in React.js Tic-Tac-Toe truly effective in improving performance?

Check out the updated version of the React tic-tac-toe game on CodePen In this version, I've included time in the move description to track when each li element was rendered: <li key={move}> <button onClick={() => this.jumpTo(move)}> ...

Modifying inner elements of a Numpy array

When working with numpy, I often create arrays like this: a = np.ones([5 , 5]) The output of this code snippet will be a 5x5 array filled with 1s. However, in certain situations, I want the outer elements to remain as 1 while the inner elements should be ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

Firefox triggers VideoJS event 'ended' at the beginning

When I use video JS, the "ended" event in Firefox is triggered both at the end and beginning of the video playback. Check out this example in FF: http://jsfiddle.net/planadecu/a3Chu/ All other browsers seem to work fine with this. The code snippet calle ...

Using Vue Composition API to invoke a child component's method that employs a render function

While using Vue composition-api with Vue2, I encountered an issue when attempting to call a method of a component with a render function from its parent component. Everything works fine without the render function. TemplateComponent.vue <template> ...

Is it possible for two different forms to invoke a single Javascript function?

I have a page with two separate formulas. Each formula has its own form with inputs, and both forms call the same Javascript function on key up. However, only the first formula seems to be working. I suspect that changing the structure of the JS file may ...