Is there a way to condense a multidimensional array into a single array that shares a common value?

Clarifying My Query:

I have a multidimensional array structured as follows

var data = [
   [2017,   1,       0,       0,       0,       0],
   [2017,   0,       0,       23,      0,       0],
   [2017,   0,       0,       0,       0,       9],
   [2017,   0,       12,      0,       0,       0],
   [2017,   0,       0,       0,       18,      0]
];

My goal is to simplify this data into the following format:

var data = [2017, 1, 12, 23, 18, 9];

Specifically:

  1. The year in Column #0 remains consistent across rows.

  2. In each row, only one element from Columns #1 through #5 will be non-zero.

Is there a straightforward approach to achieve this conversion without relying on multiple nested loops? I'm curious if there's a built-in method within JavaScript's Array type or perhaps a function available in a library that can assist with this task.

Answer №1

Iterate through the array and compare each number with the current highest number:

let numbers = [
   [10, 5, 18, 2],
   [9, 15, 7, 12],
   [4, 6, 11, 3]
];

let maxNumbers = [];

for (row of numbers) {
  for (let i = 0; i<row.length; ++i) {
    maxNumbers[i] = (!maxNumbers[i] || row[i] > maxNumbers[i]) ? row[i] : maxNumbers[i];
  }
}
console.log(maxNumbers);

result:

[10, 15, 18, 12]

Answer №2

Utilize the Array.map() function at the beginning to extract a column index, then employ reduce method to consolidate all rows into a single non-zero value within that column:

const data = [
   [2017,   1,       0,       0,       0,       0],
   [2017,   0,       0,       23,      0,       0],
   [2017,   0,       0,       0,       0,       9],
   [2017,   0,       12,      0,       0,       0],
   [2017,   0,       0,       0,       18,      0]
];

const result = data[0]
  .map((_, i) => 
    data.reduce((r, e) => r ? r : e[i], 0)
  );
  
console.log(result);

Answer №3

After considering the following two conditions:

  1. The year in Column #0 will remain constant across all rows.
  2. In each row, only one non-zero element will be present in Columns #1 through #5.

You have the option to utilize the reduce() and findIndex() functions on the inner arrays to identify the initial number greater than zero whose index is not zero. This value can then be placed at the corresponding index of the accumulated result. This approach enhances performance slightly by avoiding the need to iterate over the entire inner array during each iteration of the reduce method.

var data = [
   [2017, 1, 0,  0,  0,  0],
   [2017, 0, 0,  23, 0,  0],
   [2017, 0, 0,  0,  0,  9],
   [2017, 0, 12, 0,  0,  0],
   [2017, 0, 0,  0,  18, 0]
];

let res = data.slice(1).reduce((acc, curr) =>
{
    let found = curr.findIndex((n, idx) => n > 0 && idx > 0);
    acc[found] = curr[found];
    return acc;

}, data[0]);

console.log(JSON.stringify(res));

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

Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated referenc ...

Tips on inserting a button within a select element using jQuery

Can anyone help me with adding a button alongside the select options? I want to repeat the button and option format like this. I have been unsuccessful in my attempts so far. Any assistance would be greatly appreciated. <!DOCTYPE html> <html la ...

Enhancing XTemplate in ExtJS 4.2.1 with dynamic data refresh from store

Here's a situation that's quite unique... A DataView linked to a store is causing me some trouble. In the XTemplate, I want to display the quantity of a specific type of JSON record. Each record has a 'type' property with a value. For ...

Are there any compatibility issues when inserting an <iframe> containing HTML4 content into a HTML5 webpage?

Is there a way to gracefully add an <iframe> with HTML 4 source into a modern HTML 5 web page without causing any JavaScript or DOM conflicts? Can browsers handle the presence of different document source types without encountering errors in unique ...

Express-hbs: Dynamic Helper Function with Additional Features

I am currently utilizing express-hbs and Async Helpers in my project. However, I am facing an issue with passing options to the helper as async helpers do not seem to support this feature (or maybe I am unaware of how to do it correctly). In the code snipp ...

What is the best approach for implementing AJAX in this situation?

Here is the javascript code snippet: function addNewPerson() { var data = { 'entry_new_person_': $('#entry_new_person_1').val(), 'pop_new_person_identity_no': $(' ...

What is the reason for the browser attempting to access files via HTTPS when the host is set as 0.0.0.0?

My application was built using create-react-app. When the app is built, it generates an HTML file along with some JS and CSS files. The HTML file typically looks like this: <!doctype html>...<script src="/static/js/main.89f33fbb.chunk.js" ...

What is the reason for Promise.all() causing Array.prototype.then to be executed if it is defined?

Here is a snippet of code to consider... const array = [ Promise.resolve(1), Promise.resolve(2), Promise.resolve(3) ]; Array.prototype.then = function () { console.log('Why is this triggered?'); } Promise.all(array) .then(result => co ...

AngularJS automatically selects the first value within a select box

Is it possible to highlight the first value 'fullName' in a select box using angularjs? I am currently using angularstrap selectbox. controller, $scope.accountInfo.owners = [ { "accounts":null, "phoneumber":null, "ema ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

Create genuinely private methods within an ES6 Module/Class specifically for use in a nodejs-exclusive environment, ensuring that no data is exposed

Although there are no true private methods within ES6 classes, I stumbled upon something interesting while experimenting... While it's not possible to completely hide object properties, I attempted to follow OOP principles by dividing my classes into ...

`Python automation for seamless HTTP browsing and HTML document generation`

My weekly routine at work involves printing out Account analysis and Account Positions for more than 50 accounts every Monday. I have to navigate through the page, select "account analysis", input the account name, format the page for printing, print the o ...

Sending data using jQuery's AJAX feature

Here is an example of the code I have: var loadUrl = 'test.php'; var dataObject = { category_id: category_id, grade_val: grade }; jQuery.ajax({ type: 'POST', url: loadUrl, data: dataObject, dataType: 'html', ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...

Replicated shadows brought to life in three.js

I've been experimenting with shadows in three.js and have encountered a problem where the shadow is being cast on two faces of a mesh, as shown here. It's puzzling that the shadow from the "head" of my character is appearing on two faces of the ...

Working with Multidimensional Arrays in VueJS

Designing a virtual toaster using VueJS, where different types of bread are toasted with varying results. The toaster should be able to toast sourdough, wheat, and rye, while rejecting white and English muffins. Additionally, rye should never burn, but t ...

When using Three.js raycaster to intersect objects, it may not function properly if THREE.Points contains only one vertex or if the vertices are arranged in a straight line

I've spent quite a bit of time trying to figure out this issue. It seems that the raycaster.intersectObject( pointCloud ); method does not intersect my 'pointCloud' Object when it only has one vertex in its position array attribute with thre ...

Troubleshooting jQuery and Mootools compatibility problem in Internet Explorer 8

I am currently working on a webpage that is using both Mootools 1.4 and jQuery 1.5.1 at the same time. I understand that this setup is not ideal, but for various reasons, I have no choice in the matter. Most browsers display the page without any issues, ho ...

I'm new to this, but can someone explain why I'm being redirected to the register_db.php page when I click on the register button?

Why when I click the register button, it redirects me to the register_db.php page instead of sending the data to the database and keeping me on the same register.php page? I want the data to be sent to the database without changing the webpage. register.p ...

Are just a handful of things from my class being showcased?

Struggling with displaying all the items in my custom class created while following the Objective-C guide from Big Nerd Ranch. Specifically, it's related to Chapter 17 challenge regarding Stocks. I've reviewed solutions to similar questions but s ...