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]]
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]]
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);
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/
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);
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 ...
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 ...
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 ...
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 ...
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 ...
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 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. ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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, ...
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 ...
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 ...
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 ...