Optimal technique for dividing an array based on a specified condition when iterating through the array in JavaScript

Looking for the best approach to solve this array problem.

[ 1, -1, -1, -1, 1, -1, 1, 1 ]

I'm debating between using the reduce method, a do..while loop, or possibly something else.

The task involves looping through the array and summing up as I go. If the sum equals 0, then add those elements to a new array.

For instance, if the first two elements in the array result in 0 when added together, like [1, -1], they should be placed into a new array:

[[1, -1], [-1, -1, 1, -1, 1, 1]]

My current attempt uses the reduce method:

let hikeArr = [ 1, -1, -1, -1, 1, -1, 1, 1 ];

let newArr = hikeArr.reduce((a, b) => {
        let sum = a + b;
        if( sum == 0) {
            a.push(b)
        }
        return a;
    }, []);
    console.log("newArr", newArr);

Any suggestions on a more efficient approach?

Answer №1

Using the reduce method might not be the most efficient approach in this scenario, as it requires keeping track of multiple variables simultaneously. Instead, opting for a solution that utilizes external variables and a traditional for loop could prove to be more effective:

let hikeArr = [ 1, -1, -1, -1, 1, -1, 1, 1 ];

const output = [];
let sum = 0;
let subarr = [];
for (const num of hikeArr) {
  sum += num;
  subarr.push(num);
  if (sum === 0) {
    output.push(subarr);
    subarr = [];
  }
}
console.log(output);

Answer №2

In order to achieve the desired outcome, creating a temporary array with a closure and incorporating a variable for sum using the reduce function is essential.

const numbers = [3, 7, -2, 9, -5, 1],
    finalResult = numbers.reduce(((array, total) => (result, value) => {
        array.push(value);
        total += value;
        if (!total) {
            result.push(array);
            array = [];
        }
        return result;
    })([], 0), []);

console.log(finalResult);

Answer №3

This problem can be easily solved by utilizing the Array.reduce method.

Within the callback function of Array.reduce, each current value is added to a temporary array called subArr, and the sum is continuously calculated.

When the sum reaches 0, the contents of subArr are moved to the main result array and then reset to an initial state.

let hikeArr = [ 1, -1, -1, -1, 1, -1, 1, 1 ];


let subArr = [];
let sum = 0;
const result = hikeArr.reduce((acc, cur) => {
  subArr.push(cur);
  sum += cur;
  if (sum === 0) {
    acc.push(subArr);
    subArr = [];
    sum = 0;
  }
  return acc;
}, []);
console.log(result);

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

Express Module Employs Promises for Returns

I have a JavaScript file for elasticsearch (could be any other database as well) that performs a simple query and uses a promise to return the data. I am using this module in my Express server (server.js) with the hope of retrieving the data, as I ultimat ...

The functionality of a button within an AngularJS directive is not functioning as intended

I am trying to use a directive twice on one page. Inside the directive, there is a button that should toggle between showing the two directives when clicked. However, I'm encountering an issue where the values are not changing even though the ng-click ...

Top method for showcasing data on a webpage

Currently, I am working on developing an intranet site that retrieves test data from a database and presents the results on a standard HTML webpage. At this point, Python is configured as cgi and is providing the desired outcomes. However, there is now a ...

Reorder the Polymer dom-repeat element following a modification in the child component's value

My Polymer dom-repeat list is working fine on the initial value sorting for the children. However, when I update a value within a child element, the sort order of the list does not reflect the changes. What is the best way to achieve this? <body> ...

Creating an interactive text using Javascript functions

I am attempting to create an interactive text using JavaScript. While I can achieve this by creating a new function for each element, I realize that this approach will result in an excessive number of functions. Could anyone point out what is incorrect wi ...

Using object URL to set the source of an image is not functioning properly within the electron framework

Currently working on an electron application ("electron": "^5.0.9", running on Windows 10 version 1903) and dealing with a Node.js buffer (Uint8Array) ("node": "v10.6.0") that holds data in the format of "[255, 216, 255, 224, 0, 16,...)" with a MIME type o ...

Unable to perform queries from a separate file as connection.query function is not recognized

Currently diving into node.js and databases. Attempting a mysql query, but encountering the error TypeError: connection.query is not a function. Utilizing Node MySQL 2 (https://www.npmjs.com/package/mysql2) package; The connection and queries in app.js f ...

Why do my asynchronous callback functions seem to be returning the data requests in a different order than expected?

I am currently delving into Node.js and tackling the challenging Learnyounode course offered by Node school, which has been an amazing experience so far. However, I have hit a bit of a roadblock... The question that's tripping me up is Exercise 9 - J ...

Stopping halfway through a jQuery toggle width animation to close again

Perhaps the question may be a bit unclear, but allow me to provide an example. When repeatedly clicking the button that toggles the width, the div continues to animate long after the button press, which is not visually appealing. My desired outcome is for ...

Guide to showcasing JSON data in a .NET web service with nested arrays?

Here is the code snippet I am currently using: public class WS_Login : System.Web.Services.WebService { [WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public void Login(string userName, string password) ...

What is the best way to group all matched objects from an array based on multiple keys?

const data = [ { amount:10, gameId:7 , consoleId:3, id: 1 }, { amount:5, gameId:18 ,consoleId:3, id: 2 }, { amount:5, gameId:18 ,consoleId:3, id: 3 }, { amount:10, gameId:7 ,consoleId:3, id: 4 ...

Assign a value to the cookie based on the input from the form

I recently asked a similar question, but it seems like I missed providing some context, which is why I couldn't get it to work. My goal is to set a cookie value of a form entry when clicking on it (using the carhartl jquery plugin), but nothing happen ...

Generate visual representations of data sorted by category using AngularJS components

I am facing an unusual issue with Highcharts and Angularjs 1.6 integration. I have implemented components to display graphs based on the chart type. Below is an example of the JSON data structure: "Widgets":[ { "Id":1, "description":"Tes ...

Is there a way to adjust the width of the info panel in an SVG to automatically match the width of the SVG itself?

I am looking to place the information panel at the bottom of my SVG map and have it adjust its width according to the width specified in the viewBox. This way, even if I resize the map, the info panel will automatically adjust to fill completely based on t ...

Utilizing URL Router Parameters with Angular 4 for Enhanced Functionality

Is it possible to utilize URLs like prefix/foo-bar-1123 and prefix/foo-bar-1123/bazquux-123 with Angular 4 Router while capturing the numeric IDs? The focus here is extracting the numerical identifiers. I attempted this approach, but it resulted in groupi ...

I find myself pondering the reason behind my inability to overwrite the jquery function onRegionOver. The contents of the WAMP index.html file can

I'm curious about why I'm having trouble overriding the jquery function onRegionOver. Below is the code snippet from my WAMP index.html file. Can anyone suggest how I might use the WAMP console to troubleshoot this issue? I'm attempting to g ...

Is there a way to reach my vue instance while inside a v-for iteration?

When using a v-for loop, I encounter an error: <div v-for="index in 6" :key="index"> <div class="card h-100" style="margin-top: 200px;"> <a href="#"> <img ...

When attempting to print the elements of an array, an "undefined" value unexpectedly appeared

I recently wrote a Javascript code to display a list of items, but for some reason an unexpected undefined text is appearing before the ordered list. I am quite puzzled as to why this issue is occurring. I am wondering if there is a variable that has not ...

Use jQuery to smoothly navigate to a designated pixel position by scrolling down the page

Is it possible to use jQuery to scroll down a page to a specific pixel? I am currently working on a website with a fixed navigation bar that scrolls to an anchor point when a button is clicked, utilizing the jQuery smooth scroll plugin. The issue I am fa ...

What is the best way to submit an array of Angular Material chips when a specific form is submitted?

I need to format the form data into a JSON object like so: object { id:1, version:0, roomNo:1, availability:"available", facility:{'a', 'b', 'c', 'd'} } The image of my form can be seen below angular material chip ...