Determine the total of all numbers contained within a multi-layered array

In my nested array setup, it appears as follows:

let scores = [  
[[2, 1, 0], [2, 1, 0]],  
[[4, 2, 0]],  
[[4, 2, 0]],  
[[4, 2, 0],[2, 1, 0]]  
]  

The main goal here is to identify the highest value in each sub-array (while summing up the highest values in arrays that contain multiple arrays, such as within the first array, [[2,1,0],[2,1,0]], where we need to add up the highest values of each array resulting in 2+2.) One approach I'm considering is to either use shift() on the initial value of each array OR utilize slice()/remove to extract the lower values. This would transform my current array into this format:

newScores = [[[2],[2]], [4], [4], [[4],[2]]]

Ultimately, what I aim to achieve is represented by: output = [[4], [4], [4], [6]]

I am hopeful for some guidance in this matter! Thank you!

Answer №1

To solve this problem, you must first loop through the parent array, and for each sub-array within it, iterate over its elements to find the maximum number in each sub-array. Then, add up these maximum numbers for each child array and finally store the totals in a new output array.

let scores = [  
[[2, 1, 0], [2, 1, 0]],  
[[4, 2, 0]], 
[[4, 2, 0]],  
[[4, 2, 0],[2, 1, 0]]  
]

var output = [];
scores.forEach(function(score) {
  var total = 0
  score.forEach(function(arr) {
    total += arr.reduce(function(a, b) { return Math.max(a, b); }); 
  })
  output.push(total);
})

console.log(output); // results in [4,4,4,6]

Answer №2

 let finalScores = scores.map(groups =>
     groups.map((total, data) => total + Math.max(...data), 0)
);

Answer №3

To achieve this task, utilize the map(), reduce(), and Math.max functions alongside the spread syntax ....

let scores = [  
  [[2, 1, 0], [2, 1, 0]],  
  [[4, 2, 0]],  
  [[4, 2, 0]],  
  [[4, 2, 0],[2, 1, 0]]  
]  

const result = scores.map(a => a.reduce((r, e) => {
  return +r + Math.max(...e)
}, []))

console.log(result)

Answer №4

const gameResults = [  
[[2, 1, 0], [2, 1, 0]],  
[[4, 2, 0]],  
[[4, 2, 0]],  
[[4, 2, 0],[2, 1, 0]]  
]

function calculateScores(arr){
   let finalScores=[];
   let counter = 0;
   for(let i=0;i<arr.length;i++){
       if(arr[i].length>1){
           var a = [Math.max(...arr[i][counter])];
           var b = [Math.max(...arr[i][counter+1])];
        finalScores.push(a.map((ax,bx)=>ax+b[bx]));
       }
       if(arr[i].length===1){
            finalScores.push([Math.max(...arr[i][counter])]);

       }


   }
   return finalScores;

}
calculateScores(gameResults);

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

Align elements horizontally

Currently, I am developing a blog application using React, Material UI, and Tailwindcss. One issue I am facing is that each postcard in the grid has a different height, and I want all cards to have the same height while keeping all children aligned in the ...

Determine the value of an array element based on a specified

I am in the process of creating an array, currently consisting of a single object that is computed based on other objects from a JSON file. Sampling my code // Retrieve JSON data and convert it to an object let myFile = '{"foo": {"bar": "baz"}, "thu ...

Looking to incorporate multiple accordion drop down menus on your website? Utilize a combination of HTML, CSS, and JavaScript to

I am experiencing a challenge with implementing multiple accordion menus on my website. Whenever I attempt to duplicate the code, the new accordion menu appears but clicking on the first bar simply scrolls me back to the top of the webpage. Below is the H ...

Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up: Defining the observable for the image amount: public imageAmount: KnockoutObserva ...

populate form fields with database data using ajax

I'm currently working on populating form fields with data from a database using ajax and jQuery in my Codeigniter project. I have been able to retrieve and alert the database values into an array, which you can see in this image: alert of the data arr ...

A Reactjs function that dynamically updates state elements using two input values

In my front-end application built with react-mui, I have a list of 8 words. Each word has its state updated based on user input and can be disabled. For example: <TextField required id="standard-basic" disabled={this.state.word1Disabled} label="Word1" ...

Handling Pop-up Windows in Puppeteer using NodeJS

During my training exercises, I encountered a situation where I needed to click on a button that opens an internal "pop-up" from a specific page on Amazon. Unfortunately, Puppeteer was unable to detect this pop-up, making it difficult for me to interact wi ...

Implementing Vue components dynamically within a v-for loop based on specific conditions

My JS array is structured like this: [{type:'text', data: 'some text'},{type: 'image', data: 'link/to/image'}] Each value of type corresponds to a different Vue component (<text-block>, <image-block>). ...

Is it possible to create a dictionary from a two-dimensional array using Python?

In this 2D array, each first element is a key and the second element is a value: [['FE0456143', '218.04'], ['FB1357448', '217.52'], ['FB1482960', '222.70'], ['FB1483107', '223.32& ...

How can you transform an array of objects into an array of their corresponding IDs?

My MySQL database has a table that contains ingredients like this: id ingredient 1 egg 2 peanut 3 treenut 4 oil Now I have an array called ingredients=[peanut, oil, egg] I need to convert this array into the corresponding array of ids like this: ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Pagination Bug: Index Incorrectly Grabbed Upon Navigating to Next Pages

I encountered an issue with my paginated article list (105 articles with 10 per page). Everything works fine on the first page, but when I click on an article from page 2 onwards, it takes me to the index of the very first article in the array. <div cla ...

Tips on using the filter to display values corresponding to the selected date from the datepicker in React Js

Hello fellow developers, I've encountered an issue with filtering data based on dates using a date picker in React JS. Currently, the filtering works fine if the input date is less than the date I'm searching for. To illustrate this better, I&apo ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

Harnessing the power of $map in MongoDB for updating objects within query pipelines

After retrieving a list of objects from a call to db.collection.aggregate(), the results look like this: { _id: <some_id>, count: 400, results: [ { _id: 1, ... travel_guess: 0.1934042214126773, }, { _id: 2, ...

Is there a way to manually add a function to the Javascript/Nodejs event queue?

Suppose I want to achieve the following: function doA(callback) { console.log("Do A") callback() } function doB() { console.log("Do B") } function doC() { console.log("Do C") } doA(doC) doB() I expect the output to be: Do A Do B Do C However ...

I've come across this ajax url that seems promising, but I keep getting a GET 404 (Not Found)

I am attempting to validate using ajax and php. This is the code I have for my ajax: function PrintRecibopapel() { recibo = document.getElementById("txtCod").value; if(recibo == "") { alert("You must save the receipt before pr ...

HTML5 provides seamless transitions for videos

Interested in implementing the HTML5 video tag and JavaScript to achieve a seamless video transition, similar to a cut in a movie. I have reviewed the API at http://www.w3.org/TR/html5/video.html#tracklist If anyone has any suggestions, I would greatly ap ...

Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you. My project involves creating a web application f ...

How can I turn off credential suggestions in a React JS application?

Is there a way to disable managed credential suggestion on a React JS web page using a browser? I have tried using the autoComplete=off attribute and setting editable mode with an onFocus event, but the password suggestions are still appearing. Any help wo ...