What could be causing the data in getServerSideProps to be altered?

After fetching data from an API and passing it to index.js using getServerSideProps, I noticed that the prop array is initially in order by rank [1, 2, 3, etc].

Here's an example of the data:

[
 {rank: 1, price: 123},
 {rank: 2, price: 1958},
 {rank: 3, price: 56}
]

However, when I manipulate this data into a different variable like so:

const topPrice = data
    .sort((a, b) => a.price < b.price ? 1 : -1)
    .slice(0, 3);

The console log now shows that the original `data` is also sorted by price, even though I only intended for `topPrice` to be sorted. Why is this happening?

Answer №1

sort function changes the original list data. To prevent this, it is recommended to make a copy of your list before using the sort method

const data = [{
    rank: 1,
    price: 123
  },
  {
    rank: 2,
    price: 1958
  },
  {
    rank: 3,
    price: 56
  }
]

const topPrice = [...data]
  .sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);

console.log({
  data,
  topPrice
})

If you find it helpful, you can define a new variable to store the copied array

const data = [{
    rank: 1,
    price: 123
  },
  {
    rank: 2,
    price: 1958
  },
  {
    rank: 3,
    price: 56
  }
]

const copiedData = [...data]
const topPrice = copiedData
  .sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);

console.log({
  data,
  topPrice
})

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 is the best way to incorporate an AJAX GET request into an HTML element?

Currently, I am attempting to execute a JavaScript code that will convert all <a></a> elements found within another element <b></b> (the specific name in the HTML) into links that trigger an HTTP get request. However, the code I hav ...

Ways to generate multiple void components side by side using React

What is the most efficient method for creating multiple empty inline elements using React in a declarative manner? Suppose I need 8 empty divs, I tried the following approach but it didn't work. Is there a more effective way? render() { return ( ...

A demonstration of VueJS Nested Builder functionality

I am currently exploring VueJS and working on a project to create a simple page builder application that allows users to add sections and subsections. I am seeking guidance on how to properly set up the Vue data property for this functionality. Any advice ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

Are there options available in nightwatchjs for making intricate decisions with selectors?

When using the NightWatch JavaScript Selenium tool, it is important to establish good practices for identifying different parts of the GUI before running tests. For example, distinguishing between options A and B and creating separate tests accordingly. An ...

Can you provide guidance on utilizing OneNote JavaScript APIs to interpret indented paragraphs within OneNote?

I keep a notebook that contains the following entries: https://i.stack.imgur.com/MLdO0.png For information on OneNote APIs, you can refer to this link (paragraph class selected already) https://learn.microsoft.com/en-us/javascript/api/onenote/onenote.p ...

Sometimes, React doesn't cooperate properly in the callback function of a setState operation

Imagine this scenario: callback = () => { ... } When is it appropriate to use this.setState({...}, this.callback); and when should I opt for this.setState({...}, () => { this.callback(); }); In order to maintain the validity of this within the ...

Manipulate the value of the <input> element when focused through JavaScript

After I focus on the input field, I was expecting to see Bond-Patterson, but instead, I am only getting Bond. What could be causing this discrepancy and how can it be fixed? $('input[name="surname"]').attr("onfocus", "this.placeholder='Bo ...

A guide to efficiently fetch JSON data synchronously using AngularJS

Trying to fetch data from a JSON file using AngularJS results in an error due to the asynchronous nature of the call. The code moves on to the next step before receiving the data, causing issues. The $http.get method was used. $http.get('job.json&apo ...

My type is slipping away with Typescript and text conversion to lowercase

Here is a simplified version of the issue I'm facing: const demo = { aaa: 'aaa', bbb: 'bbb', } const input = 'AAA' console.log(demo[input.toLowerCase()]) Playground While plain JS works fine by converting &apo ...

Here's a method to extract dates from today to the next 15 days and exclude weekends -Saturday and Sunday

Is there a way to generate an array of dates starting from today and spanning the next 15 days, excluding Saturdays and Sundays? For example, if today is 4/5/22, the desired array would look like ['4/5/22', '5/5/22', '6/5/22' ...

Node.js application - varying NODE_ENV upon NPM launch

Operating my node.js application can be quite confusing. When launched by npm start, it operates in "production" mode, whereas when launched using node start.js, it runs in 'development' mode. I want to ensure that the 'development' mo ...

I am unable to loop through and display the buttons

I have a button object within my component that I want to iterate through and display all the buttons {0: {…}, 1: {…}, isActive: true} 0: {key: ':R2m:', text: 'Trading', isActive: true} 1: {key: ':R2mH1:', text: 'Ba ...

Using JavaScript to send formatted text through POST requests in a Rails application

Within APP A, I have the following formatted text: A beautiful painting because I created it because an artist endorsed it because my cat loves it I can access this formatted text in index.html.erb through product.body_html, which I then load into a Ja ...

NodeJS server connection delay

My server has an Express NodeJS instance installed. The API stops responding when it is overloaded, leading to the following response: POST /my/api/result - - ms - - I attempted the following in ./bin/www: server.on('connection', function(sock ...

Recreating dropdown menus using jQuery Clone

Hey there, I'm facing a situation with a dropdown list. When I choose "cat1" option, it should display sub cat 1 options. However, if I add another category, it should only show cat1 options without the sub cat options. The issue is that both cat 1 a ...

Seeking guidance on how to retrieve an image from Firebase storage using NextJs. Any suggestions on how to tackle this issue

Here is the code snippet we are currently utilizing in Nextjs to facilitate image downloads: const handleDownload = async (fileUrl: string) => { try { const storageRef = ref(storage, fileUrl); const downloadURL = await getDownloadURL(storageRe ...

Problems with radio button serialization in jQuery form plugin

I've created a basic form: <form class="dataform" method="post" id="settings" action="/"> <input type="radio" name="shareSetting" value="n"/> <input type="radio" name="shareSetting" value="y"/> <input type="button" na ...

The scroll header remains fixed in size despite being responsive

I've been struggling to resize a fixed header when the page is scrolled. Unfortunately, I'm having trouble getting the header to adjust its size as the scrolling happens. $(document).scroll(function() { navbarScroll(); }); function navbarSc ...

Troubleshooting Chakra UI problems within a pre-existing Nextjs and Redux Toolkit application

Seeking assistance in resolving a warning related to the usage of the ChakraProvider component "Warning react-dom.development.js:86 Warning: You are importing hydrateRoot from "react-dom" which is not supported. It is recommended to import ...