Implementing JavaScript logic to proceed to the following array within a 3D array once a specific condition is met

I'm currently tackling a challenge that requires me to obtain a specific number using a given 3D array. This array consists of 2D arrays, each containing the same number repeated x times. The parent array is sorted from largest to smallest.

Here's an example of the parent array;

array = [
 [5, 5, 5, 5, 5, 5],
 [4, 4, 4],
 [3, 3, 3, 3],
 [1, 1, 1, 1, 1, 1, 1],
];

The target number I need to achieve is 27;

let number = 0;
for (let i = 0; i < array.length; i++){
 for (let j = 0; j < array[i].length; j++){
 number += array[i][j]
 }
}

The current for loop adds up all the numbers in the parent array, but I want it to stop iterating when it exceeds 27 and precisely hit the number 27.

In the example given above, during the first iteration, it should continue until it reaches 25 and then move on to the second iteration; the second and third iterations are skipped because the sum must be exactly 27; finally, it breaks during the second run of the fourth iteration when the total becomes 27;

I apologize for this verbose explanation, my understanding of JavaScript is limited so I tried my best to articulate it clearly.

Answer №1

let targetValue = 27; // Modify this value as needed

let totalNumber = 0;
let helpingHands = []

for (let x = 0; totalNumber < targetValue && x < numArray.length; x++){
    assist = []
    for (let y = 0; totalNumber < targetValue && y < numArray[x].length; y++){
        if ( totalNumber + numArray[x][y] <= targetValue ) {
            assist.push(numArray[x][y])
            if ( ( totalNumber += numArray[x][y] ) == targetValue ) {
                helpingHands.push(assist)
                assist = []
                console.log( `Located target ${targetValue} at x=${x}, y=${y}` );
                break;
            }
        }
    }
    if (assist.length) {
        helpingHands.push(assist)
    }
}

console.log(helpingHands)

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

In my Flask Bootstrap website, the navigation bar remains unchanged by the presence of Javascript

I am currently in the process of creating a navigation bar for my Flask website using Bootstrap. However, when I implemented it into my HTML code, it is not displaying correctly which leads me to believe that the JavaScript may not be functioning properly. ...

Unable to dynamically display an HTML5 video using JavaScript

I'm facing an issue with displaying videos in a modal dynamically. Here's the scenario: +------------+---------+ | Name | View | +------------+---------+ | 1.mp4 | X | | 2.mp4 | X | +------------+---------+ The X ...

Invoking a HTTP request in a web service using the link method

Upon the initial page load, a successful RESTful call is made to retrieve data. However, when clicking on the left navigation links that display this data, another RESTful call needs to be made. I am attempting to achieve this functionality within the link ...

Issue with Angular modal text boxes failing to populate using ngModel

I am facing an issue with populating data in a modal when a table row is clicked. The table contains TV show data and uses dir-paginate/ng-repeat to display the information. However, when I click on a row to edit the show, the ng-model data does not load i ...

Error: Conditional formatting not compatible with JavaScript detected

I have a jQuery DataTable that is populated with data from a JSON file. Everything works smoothly, but I'm encountering an issue with conditional formatting. The script I'm using assigns a 'positive' class to all cells in column 2, even ...

When attempting to use $.ajax to send JSON, it instead sends a query string

I'm having an issue where I'm using ajax to send JSON data with the following script: var sendData = {"test":"opa"}; console.log(sendData); $.ajax({ contentType: "application/json", method: "POST", url: "/test", dataType: "json", ...

Ways to loop through an array of daytime values and exhibit just the records for the current week

ng-repeat="day in task.DailyWorks | limitTo : weekdays.length: weekStart" This iteration process enables me to showcase the daily work records in a structured format within the table columns. The feature allows for seamless navigation between different we ...

What is the process of setting up a subelement in a Vue array?

I am currently working on incorporating an array read feature using Vue.js: {{ this.locations[this.record.carton.LocationID - 1].Location }} Although the code functions properly during runtime, it throws an error upon initial loading: app.js:55125 [Vue wa ...

Regular expressions or regex can be used to match the initial letter or letters of various words

Struggling with regex? After searching for an hour, the best solution found was this one. Still unable to crack it though... Here's what I need: Have a JS array that needs to be filtered. The array looks like: [ 'Gurken halbiert 2kg', &a ...

Perform a series of tasks concurrently within a function using Grunt

I am currently utilizing grunt-shell along with other custom tasks in my project. In one of my tasks, I need to execute these tasks sequentially and verify the output of each task. Here is a simplified representation: grunt.task.registerTask('test&ap ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

When a dropdown list only contains one item, the jQuery change event does not get triggered

I'm currently exploring ways to trigger events when options in a dropdown menu are clicked. I haven't come across any clear explanations on how to achieve this. What I specifically need is to activate the event and utilize the selected value. Usi ...

Can an inner promise in JavaScript not be caught by another promise?

When using promises, I am encountering an issue where the "catch" doesn't seem to catch its child promises. This results in me having to include two instances of the "catch" block. Facility.userHaveAccess(locationObject.created_by, locationObject.fac ...

What could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...

Ways to divide and extract information stored within an array

I need help printing out this array of data. Here is how my data is structured: [[["Not Critical","Not Critical"]],[["Not Critical","Not Critical"]],[["Not Critical","Not Critical"]]] This is how I want the data to be displayed (each innermost value on ...

Every time I click once, two unnecessary AJAX calls are triggered, and the DOM remains outdated until I manually refresh the page

Whenever I click on a span, it sends an ajax request to delete the clicked todo from the database. However, in the DOM, the item is not removed until I refresh the page. Here is my index.html file: <ul class="list"> </ul> I noticed ...

Retrieving Dropdown Values based on Selection in Another Dropdown

On my website, there are two dropdown lists available: 1) One containing Book Names 2) The other containing Links to the Books. All data is stored in an XML file structured like this: <?xml version="1.0" encoding="UTF-8"?> <BookDetail> <boo ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

trouble with fetching data

Within my Backbone view, I have the following code snippet: var BookView = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.model.fetch({ success : function(model, resp, opt) { alert(this.$el. ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...