Using Javascript's Array.reduce() function causes the page to crash with Error Code 6

Everything runs smoothly on the webpage unless I provide an initial value, causing a TypeError due to only one remaining element (as expected). In an attempt to fix this, I decided to pass 0 as the initial value for the reduce function (line 4 in the code snippet below). Unfortunately, this action results in the entire page breaking with error code 6.

The goal I'm aiming for: My objective is to sum all elements within an array, append that sum to another array, eliminate the first element, and repeat the process until no elements remain. At that point, I want the reduce() function to return 0, hence my need to supply an initial value of 0.

function partsSums(ls) {
  let sumArr = [];
  while (ls.length >= 0) {
    sumArr.push(ls.reduce((acc, cur) => acc + cur, 0));
    ls.shift();
  }
  return sumArr;
}

partsSums([0, 1, 3, 6, 10]);

The desired output I am seeking: [20, 20, 19, 16, 10, 0]

https://i.sstatic.net/rbsSJ.png

Answer №1

Here is a method you can use:

function calculateSums(inputList)
  {
  let sumArray = []
    , lengthOfList    = inputList.length
    ;
  while ( lengthOfList >= 0)
    {
    sumArray.push(inputList.reduce((accumulator, current) => accumulator + current, 0))
    inputList.shift()
    --lengthOfList
    }
  return sumArray
  }

console.log(JSON.stringify( calculateSums([0, 1, 3, 6, 10])  ))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

There is a critical issue in your code with the condition ls.length >= 0. This condition is causing an infinite loop to occur. To fix this, simply change it to ls.length > 0

Recommendation

It appears that you are aiming for a cumulative summation from right to left. However, the current implementation of your function is not very efficient. Consider using suffix-sum as a better approach to solve this problem.

const suffixSum = arr => {
  const res = [];
  const {length} = arr;
  res[length] = 0;

  for (let i = length - 1; i >= 0; i--) {
    res[i] = res[i+1] + arr[i];
  }
  
  return res;
}

console.log(suffixSum([0, 1, 3, 6, 10]));

The suggested algorithm has a time complexity of O(n), whereas your current algorithm has a time complexity of O(n^2).

Answer №3

It has been highlighted in the responses that you are encountering an infinite loop due to the fact that the array's length will never drop below 0.

As illustrated in alternative solutions, you can resolve this by adjusting the condition to ls.length > 0. However, by doing so, you will miss the scenario where you need to insert 0 into the result during the last iteration when the array is empty.

Rather than checking the length within the while() condition, evaluate it after executing reduce() and then break out of the loop accordingly.

function splitIntoParts(ls) {
  let totalArr = [];
  while (true) {
    totalArr.push(ls.reduce((acc, cur) => acc + cur, 0));
    if (ls.length == 0) {
      break;
    }
    ls.shift();
  }
  return totalArr;
}

console.log(splitIntoParts([0, 1, 3, 6, 10]));

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

Extracting textual information from Wikipedia through iframes?

Currently, I am working on a website project utilizing Squarespace. This site will feature multiple pages dedicated to individuals who have reached a level of notability worthy of having their own Wikipedia page. With over 150 pages planned, manually writi ...

Tips for managing CSS/style conflicts in JavaScript/AngularJS applications

I am new to AngularJS and I have a requirement to assign CSS properties to a component at the JavaScript file level. When I debug my code after applying the CSS styles to the component, I can see that all the applied CSS properties are behaving as expected ...

A JavaScript right-click menu that updates a variable when clicked

Within my three-dimensional application created with three.js, I have implemented a functionality where right-clicking on floors (BoxGeometry) triggers a context menu to select from various textures. While this feature works as intended for a single floor, ...

What would be the JavaScript counterpart to python's .text function?

When using Element.text, you can retrieve the text content of an element. Recently, in a separate discussion on SO, there was a Python script discussed that scraped data from the followers modal of an Instagram account. The script is designed to capture t ...

Guide on how to beautify HTML and generate output files in the identical directory as the current one

Hey there! I'm currently working as a junior front-end developer and have recently delved into using gulp. One of the challenges I face is dealing with HTML files received from senior developers that aren't well-formatted, containing excessive wh ...

Issue with React form not appearing on web browser

I'm having trouble getting the form to show up on the browser. For some reason, the formComponentDict variable is not displaying any of the form steps. Can anyone point me in the right direction? Any assistance would be greatly appreciated. Thank you ...

Interact with various div elements bearing the same class name through mouse movements

I am trying to implement a mousemove effect on multiple divs with the same class name but facing an issue where the mouse position doesn't restart inside each div. If you want to see a demo of what I'm describing, click here. Below is the code ...

Using Vuetify to send a parameter from a select option to a method as a parameter

Just starting out with vuejs and encountering an issue passing parameters from a selected option to my JavaScript method. In my updateClientIsMaster method, the item is always undefined. However, when I added v-on:change="updateClientIsMaster in the & ...

The requested file cannot be accessed using XMLHttpRequest.open url

Currently, I am in the process of learning about AJAX by following the MDN tutorial. However, I have encountered an issue with the first sample code provided to fetch test.html. Regardless of whether I use absolute or relative paths, my local server consis ...

Angular Square Grid Design

Attempting to create a square grid layout using CSS for ng-repeat items. Essentially, I am looking to have one big square followed by four smaller squares that combined have the same width and height as the big square. Here is my CSS: .container{ widt ...

What methods can I use to streamline integration with minimal lines of code?

Seeking help with JavaScript: Recently dived into JavaScript and managed to create the desired functionality for my navigation menu. However, I suspect that my code is not optimized as I find myself repeating lines unnecessarily. Here's a snippet of ...

JavaScript code often contains dates that are formatted in various ways

I need to perform validation in JavaScript by comparing DATES and TIME. I need to have the date in dd/MM/yyyy format, but I am unsure of the format it is currently taking. After debugging the JavaScript code, I discovered the format. The screenshot below ...

What is the correct approach for detecting object collisions in Phaser 3?

Hey everyone, I'm facing a problem and could use some assistance. Currently, I am trying to detect when two containers collide in my project. However, the issue is that the collision is being detected before the objects even start moving on screen. It ...

Modify the location of the input using jQuery

Hey there, I've got this snippet of HTML code: <div class='moves'> <div class='element'><input type='text' value='55' /></div> <input class='top' type='text&apo ...

What is the best way to showcase an array's contents on a form?

I need some assistance with properly displaying the array output in a form using C# programming. I believe it is just a simple fix, but as a newcomer to C#, I am struggling to identify my mistake. class Program { public static void Menu () ...

Combining two fetching objects to deliver a response to a React application using Node.js and MongoDB

Hey there, I'm just getting started with node.js and I'm facing a challenge. I have two collections with different amounts of data and I need to send a response to the client-side with the combined information. I've attempted to merge these ...

Utilizing the default validation in Bootstrap 4 to ensure proper email format in form submissions

Can anyone assist with validating an email form field using Bootstrap 4 without the need for any additional libraries? I believe it might require a simple JavaScript function at the end of the document to check if the fields match. Any guidance on this mat ...

Unable to retrieve variable declared externally from Switch Statement

Having an issue with assigning a value to the variable contactNumber inside a switch statement. Upon reaching the assignment line, an error SyntaxError: Unexpected identifier is triggered within the switch statement context. function contactMessageForCo ...

What is the best way to extract a value from two different HTML identifiers?

Something tells me that this task is quite simple. I just need some guidance on what I might be missing here. All I really want is a basic program that can extract the content from <span id "text"> and paste it into <div id="text2">. funct ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...