Arranging arrays within an array

I currently have an array of arrays that I need to sort based on the date value within one of the arrays. Here is the example:

This is the initial array:

arrayOfArray = [
  ["Date", "01/02/2017", "02/02/2016"],
  ["Temperature", "19", "16"],
  ["Humidity", "80%", "86%"]
]

I want to sort it like this:

newArrayOfArray = [
  ["Date", "02/02/2016", "01/02/2017"],
  ["Temperature", "16", "19"],
  ["Humidity", "86%", "80%"]
]

The sorting should be done based on the date array in descending order. How can I achieve this? Thank you in advance.

Answer №1

One way to approach this is by utilizing the concept of sorting with map, where you can specify a particular array as a reference for sorting and then reconstruct the array based on this pattern.

var array = [["Date", "01/02/2017", "02/02/2016"], ["Temperature", "19", "16"], ["Humidity", "80%", "86%"]],
    selected = array[0],
    temp = selected.slice(1).map(function (_, i) { return i + 1; });
    
temp.sort(function (a, b) {
    function getISO(d) { return d.replace(/(..)\/(..)\/(....)/, '$3-$2-$1'); }
    return getISO(selected[a]).localeCompare(getISO(selected[b]));
});

temp.unshift(0);
array = array.map(function (a, i) {
    return temp.map(function(index){
       return array[i][index];
    });
})

console.log(array);

Answer №2

To simplify the process, you can condense it into another array by adding elements while organizing the values from the first index.

let arr = [
  ["Date", "01/02/2017", "02/02/2016"],
  ["Temperature", "19", "16"],
  ["Humidity", "80%", "86%"]
];

function getISO(d) {
  return d.replace(/(..)\/(..)\/(....)/, '$3-$2-$1');
}
let m = arr.reduce((a, b) => {
  let [n, ...rest] = b;
  if (n === 'Date') {
    rest.sort((x, y) => Date.parse(getISO(x)) - Date.parse(getISO(y)));
  } else {
    rest.sort((x, y) => parseInt(x) - parseInt(y));
  }
  a.push([n, ...rest]);
  return a;
}, []);
console.log(m);

I utilized Nina's getISO function to ensure that the Date.parse properly functions in all settings.

Answer №3

Your current data structure may not be the most efficient when it comes to sorting. Consider restructuring it to a data per date format:

var dataPerDate = [];
var [dates,temp,humidity] = arrayOfArrays;
dates.forEach((date,i)=>{
  if(!i) return;
  dataPerDate.push({
    date,
    temp:temp[i],
    humidity:humidity[i]
  };
});

With this new structure, sorting becomes much simpler:

dataPerDate.sort(
 (a,b)=>new Date(a.date) - new Date(b.date)
);

Answer №4

One approach that incorporates MDN's suggested method for utilizing map() within sort():

let arrayOfArrays = [
  ["Date", "01/02/2017", "02/02/2016"],
  ["Temperature", "19", "16"],
  ["Humidity", "80%", "86%"]
]

function sortByDate(outer) {
  const [ [label, ...values], ...rest ] = outer
  const dates = values.map((value, index) => {
    // convert date string to number
    const time = Date.parse(value.replace(/(..)\/(..)\/(....)/, '$3-$2-$1'))
    
    // create an object to store original index and value
    return { time, index, value }
  }).sort((a, b) => a.time - b.time)
  
  // return sorted dates with other subarrays re-ordered accordingly
  return [
    [
      label,
      ...dates.map(date => date.value)
    ],
    ...rest.map(([label, ...inner]) => [
      label,
      ...inner.map((value, index) => inner[dates[index].index])
    ])
  ]
}

console.log(sortByDate(arrayOfArrays))

Answer №5

If you're looking to improve your code, one suggestion is to utilize an object for storing the data and then create a custom sort function based on the date of that object. Here's an example:

var Datapoint = function (date, temp, humidity) {
  this.date = date;
  this.temp = temp;
  this.humidity = humidity;
};

var array = [
  new Datapoint(new Date(2017, 1, 1), 19, 80),
  new Datapoint(new Date(2016, 1, 2), 16, 86),
  new Datapoint(new Date(2017, 0, 2), 13, 88),
  new Datapoint(new Date(2017, 1, 1), 21, 76)
];

array.sort(function (a, b) {
  return a.date > b.date ? 1 : a.date < b.date ? -1 : 0;
});

// Just for representation
Datapoint.prototype.toString = function () {
  var dateString = this.date.getDate() + "/" + (this.date.getMonth() + 1) + "/" + this.date.getFullYear();
  return "Date: " + dateString + ", temperature: " + this.temp + "&deg;, humidity: " + this.humidity + "%";
};

document.getElementById("result").innerHTML = array[0].toString() + "<br/>" + array[1].toString() + "<br/>" + array[2].toString() + "<br/>" + array[3].toString();
<div id="result"></div>

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

Configure gulp tasks based on the environment variable NODE_ENV

Is it possible to set up a specific gulp task based on the value of NODE_ENV? For instance, in my package.json file, I currently have: "scripts": { "start": "gulp" } Additionally, I have various gulp tasks defined such as: gulp.task('developm ...

The total number of items in the cart is experiencing an issue with updating

For a recording of the issue, click here: While everything works fine locally, once deployed to production (vercel), it stops working. I've tried numerous approaches such as creating a separate state in the cart, using useEffect with totalQuantity in ...

Updating a marker's latitude and longitude using Laravel, Google API, and Ajax: A step-by-step guide

I'm struggling with sending the marker coordinates to a controller using ajax. I have named my routes 'update-marker-position' and included csrf_token(), but I am still seeing an error message in the logs. In my web.php file: Route::post(&a ...

Guide on setting up a React project using a customized version of create-react-app

Is there a way to specify the version of create-react-app when creating a new React application? I want to use version 1.0.10 specifically, but when I run create-react-app myProject, it always defaults to the latest version available at that time. ...

Challenges arise when using ui-select with both multiple selection and asynchronous options

I'm encountering an issue with the ui-select directive (using AngularJS 1.6.4 and Ui-select 0.19.8). You can find my created fiddle here. The dropdown is supposed to display contacts when I type more than 3 characters, without any filtering applied ...

Unable to retrieve observable modifications

In my code file for handling reports, named report.service.ts, I have a method that retrieves reports data. This method simply returns a constant array of report objects from a mock source. Here is the implementation: @Injectable() export class ReportServ ...

Typescript headaches: Conflicting property types with restrictions

Currently, I am in the process of familiarizing myself with Typescript through its application in a validation library that I am constructing. types.ts export type Value = string | boolean | number | null | undefined; export type ExceptionResult = { _ ...

Grabbing data using @RequestParam and $http.post in angularjs I will

I need help sending an array arr=["xxx.yyy","zzz.vvv"] over to a spring endpoint in this manner: $http.post("url",arr) On the spring side, I have the following setup: @PostMapping(value = "url") public Set<String> func(@RequestParam(name="ar ...

HTML textarea content will update automatically whenever there is an input change in JavaScript

Everything seems to be working as expected, but I noticed that the onmouseover event only triggers once. Is there a way to make it work multiple times, i.e., every time the text array changes? <html> <head> <script> function myFunct ...

Having trouble with the Document.createElement function not functioning properly when trying to download a

ISSUE While my PDF download feature functions properly in Chrome, it encounters difficulty when attempting to work in IE 11/10/9. When using IE, I receive a security warning prompt. After selecting Yes to allow the download, nothing happens. SOURCE CODE ...

Tips for eliminating blank rows from _POST following a PHP and JQuery post

My AJAX jQuery post is working fine, but the result looks like this: Array ( [facdatas] => Array ( [0] => Array ( [mbr_id] => 26 ) [1] => Array ( ...

Skip ahead button for fast forwarding html5 video

One of the features in my video player is a skip button that allows users to jump to the end of the video. Below is the HTML code for the video player: <video id="video1" style="height: 100%" class="video-js vjs-default-skin" controls muted autoplay=" ...

Methods for extracting the result of a promise

Struggling with a project and in need of some assistance: Within a function, I have a promise and I am trying to figure out how to return the value of "current" so that I can utilize it elsewhere. My task involves retrieving data from Firebase, shuffling t ...

Looking for a more efficient method to pass components with hooks? Look no further, as I have a solution ready for

I'm having trouble articulating this query without it becoming multiple issues, leading to closure. Here is my approach to passing components with hooks and rendering them based on user input. I've stored the components as objects in an array an ...

What is the best way to merge shared information within a JSON object while utilizing the Map()

Here is some JSON Data for reference: { "+2555970315763":{ "uid": "u9weKk62GvXu4Yf66HM2TFXDL5S2", "phoneNumber": "+2555970315763", "lastTime": "Mon ...

Encountering NaN values in JavaScript arrays

I'm facing an issue with my HTML code that is supposed to make ball(s) bounce around the canvas. However, when I set the arrays storing the coordinates to random positions and test with alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));, it retur ...

Distinguishing each unique JavaScript property within an array of objects

I've been struggling with this problem for quite some time. I have an array of objects, focusing on the "00" object at the moment, and I am trying to group together the bestScore properties in a specific way: .. User Group apple .. User Group ba ...

Issue with NPM's manual review process following recent package updates

Upon downloading node-sass, I encountered the following warning message: "found 9 vulnerabilities (4 moderate, 5 high) in 1869 scanned packages. 9 vulnerabilities require manual review. See the full report for details." Despite attempting to manually insta ...

Is the JavaScript progress bar dysfunctional when used with object-oriented JavaScript code, but functions properly with arrow functions?

After posting a question about the JavaScript progress bar not working with object-oriented JavaScript code on Stack Overflow, I decided to try rewriting the script using arrow functions. Here is the new code: document.getElementById("barButton").addEve ...

Spring Security does not generate an error if the authorization header is missing following a login using AngularJS

Working on implementing HTTP Basic Authentication using Spring Security and Angular JS by including the Authorization header in $http headers: const headers = { authorization: "Basic " + btoa(this.login + ":" + this.password) }; this._$http.get("user ...