Steps for transforming an array into a complex array

Here is an array I have: [2, 1, 2, 1, 1, 1, 1, 1]

I am looking for a way to create new arrays within the original array when the sum of values exceeds four.

The desired result should look like this: [[2,1],[2,1,1],[1,1,1]]

Answer №1

If you want to perform a task that involves adding values from arrays, you can utilize the Array#reduce method. This method allows you to add values of the last inserted array as well as the entire result array.

The key part of the algorithm is encapsulated in this line of code:

!i || r[r.length - 1].reduce(add, 0) + a > 4 ?
    r.push([a]) :
    r[r.length - 1].push(a);

Here, a condition is checked: if the index i is zero or if the sum of the last array of the result combined with the current item exceeds 4, a new array containing the current value is created. Otherwise, the element is simply added to the last array.

var data = [2, 1, 2, 1, 1, 1, 1, 1],
    add = function (a, b) { return a + b; },
    result = data.reduce(function (r, a, i) {
        !i || r[r.length - 1].reduce(add, 0) + a > 4 ? r.push([a]) : r[r.length - 1].push(a);
        return r;
    }, []);

console.log(result);

Answer №2

If you want to create a new array by looping through the existing one and pushing elements into it based on a certain condition, you can follow this approach:

var originalArray = [3, 1, 2, 2, 1, 1, 2, 2];

var newArray = [];
var tempArray = [];

for (var index = 0; index < originalArray.length; index++) {
  if (calculateSum(tempArray) + originalArray[index] > 5) {
    newArray.push(tempArray);
    tempArray = [];
  }
  tempArray.push(originalArray[index]);
  if (index == originalArray.length - 1) newArray.push(tempArray);
}

function calculateSum(array) {
  return array.reduce(sum, 0);

  function sum(a, b) {
    return a + b;
  }
}

Check out the live demo here: https://jsfiddle.net/e762tuhd/

Answer №3

To simplify the process...

let numbers = [2, 1, 2, 1, 1, 1, 1, 1];
let temporary=[];
let finalOutput=[];
let totalSum=0;
for(let index=0; index<numbers.length; index++){
totalSum += numbers[index];
if(totalSum<=4){
temporary.push(numbers[index]);
}else{
finalOutput.push(temporary);
totalSum = numbers[index];
temporary=[numbers[index]];
}
}
finalOutput.push(temporary);
console.log(finalOutput);

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

Guide on deleting an element from an object array based on the content of a specific field (resulting in undefined mapping)

I am working on integrating a task list feature using React. I have created a state to store the id and content of each task: this.state = {tasks: [{id: 123, content: 'Walk with dog'}, {id: 2, content: 'Do groceries'}]} Adding elements ...

Using the fieldset element in AngularJS Material causes disruptions in my flex layout

My current issue can be illustrated through two code examples: The first example functions properly when the fieldset is not included. In the second example, including the fieldset causes the layout to extend beyond the window when there is long text (in ...

The challenge with Normalizr library in Redux and how to address it

I am currently attempting to utilize the Normalizr library by Paul Armstrong in order to flatten the Redux state. Below are the schema definitions: import { normalize, schema } from 'normalizr' const fooSchema = new schema.Entity('foos&apo ...

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...

Conflicting behavior between jQuery focus and blur functions and retrieving the 'variable' parameter via the $_GET method

There is a simple focus/blur functionality here. The default value shown in the 'Name of Venue' input field changes when the user clicks on it (focus) and then clicks away(blur). If there is no text entered, the default value reappears. Input fi ...

Calling http.get one after the other without knowing the length of the list

Suppose I have a list of URLs as follows: var myurls = ['http://server1.com', 'http://server2.com', 'http:sever2.com', etc ] Each URL is considered a "fallback" and should only be used if the previous one is unreachable. Thi ...

Why can't we import Angular 4 as a library similar to AngularJS?

Why was AngularJS introduced as a script to import in an HTML page? However, in the newer version Angular 4, we need to use a web server to launch the application? Is it because AngularJS is not considered a framework but Angular 4 is? Thank you. ...

Bcrypt.compare function working in code but not functioning in chai/mocha tests

I have integrated node.js backend into my project. For encrypting passwords, I am utilizing the bcrypt library. To compare the string password from the request with the hashed password in the database, I am using the bcrypt.compare function. The bcrypt.com ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

Using JS/AJAX to update a section of a webpage when a button is clicked

Currently, I am working on developing a generator that will display a random line from a .txt file. Everything is going smoothly so far, but I have encountered an issue - I need a specific part of the page to refresh and display a new random line when a ...

The iFrame is set to a standard width of 300 pixels, with no specific styling to dictate the size

My current challenge involves utilizing the iframe-resizer package to adjust the size of an iframe dynamically based on its content. However, even before attempting any dynamic resizing, I encounter a fundamental issue with the basic iframe: it stubbornly ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

What steps do I need to follow in order to perform a particle design simulation on my laptop

Recently, I attempted to utilize some of the particle designs featured on this website https://speckyboy.com/particle-animation-code-snippets/, but encountered difficulties. I have included both the stylesheet and javascript files, yet the design does not ...

When using Mongoose and Socket.IO, an empty string will not be printed if the result is empty

I'm facing an issue with a filter I created using socket.io and mongoose. Specifically, I'm trying to display a message if there are no results returned when querying, but it seems to not be working as expected. Restaurant.find({ $text : { $sear ...

Implementing an interactive tab feature using jQuery UI

Recently, I was working on a project involving HTML and jQuery. Now, my goal is to create a dynamic tab with specific data when a button is clicked. This is my code for the JQuery-UI tab: $(document).ready(function() { var $tabs = $("#container-1 ...

Incorporating an array of JSON into a Mongoose schema in JavaScript

I am currently developing an Android App focused on baseball, and I have decided to use MongoDB to store my data. The format in which I would like my JSON data stored in the database is as follows: {"<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Optimal approach for reutilizing Javascript functions

After creating a simple quiz question using jQuery, involving show/hide, addClass, and tracking attempts, I am now considering how to replicate the same code for multiple questions. Would it be best practice to modify all variables in both HTML and jQuery, ...

What is the best way to loop through an array inside an object stored within another array using *ngFor in Angular 2?

Overview: My game data is structured as an array called 'game' with seven objects representing each round. Each round object contains details like 'roundNumber', 'title', 'players', and 'winner'. The &apos ...

Capturing attention within react-bootstrap drop-downs and pop-ups

Currently, I'm focused on enhancing accessibility features and I have a specific goal in mind: to confine the focus within a popover/dropdown whenever it is opened. Working with react-bootstrap, my inquiry revolves around finding out if there's ...

Transforming a jQuery menu into an active selection with Vue JS

I am looking to transition away from using jQuery and instead utilize Vue for the front end of a menu. Specifically, I need to add an active class and a 'menu-open' state to the appropriate nested list items, similar to what is achieved in the pr ...