What is the most efficient way to organize these arrays?

I've been racking my brain trying to figure out a sorting logic for some arrays, but I'm stumped. Maybe you have an idea?

Imagine we have an array of objects structured like this:

let obj = {day:'2', month:'6', year:'1938' }

The array would look something like this:

let array = [{year:'1938, month:'6', day:'3'},{year:'1935', month:'5', day:'3'},{year:'1935, month:'', day:''}, {year:'1935', month:'5', day:''}, {year:'1934}, month:'3', day:''}, {year:'1934', month:'3', day:'15'}, {year:'1934}, month:'', day:''}]; 

I want the sorted array to look like this:

let sortedArray = [{year:'1934}, month:'', day:''},{year:'1934}, month:'3', day:''},{year:'1934}, month:'3', day:'15'},{year:'1935, month:'', day:''},{year:'1935', month:'5', day:''},{year:'1935', month:'5', day:'3'},{year:'1938, month:'6', day:'3'} 

The year, month, and day fields are not required in my app, but I want to display them sorted chronologically starting with objects that only have the year, then those with year and month, and finally those with all three elements. This helps me build a timeline.

I tried creating 3 separate arrays - one for objects with only years, one for those with years and months, and another for objects with all fields filled.

My approach looked something like this:

 // code snippet

Unfortunately, my logic hit a roadblock when I had to compare months between different arrays. If there's a solution to sort the array as described, your help would be greatly appreciated. Thank you!

Answer №1

You may want to experiment with filtering the groups, converting each to a date, and then sorting them within each group.

There is potential for enhancement in this code snippet.

const array = [
  {year:'1938', month:'6', day:'3'},
  {year:'1935', month:'5', day:'3'}, 
  {year:'1935', month:'', day:''}, 
  {year:'1935', month:'5', day:''}, 
  {year:'1934', month:'3', day:''}, 
  {year:'1934', month:'3', day:'15'}, 
  {year:'1934', month:'', day:''}
];

const yearSort = array => {
  return array.filter(item => item.year && !item.month && !item.day).map(item => { 
    return {
      item,
      date: new Date(parseInt(item.year),0,1)
    }
  }).sort((a,b) => a.date < b.date ? -1 : 1)
      .map(i => i.item)
}

const yearMonthSort = array => {
  return array.filter(item => item.year && item.month && !item.day).map(item => { 
    return {
      item,
      date: new Date(parseInt(item.year),item.month - 1,1)
    }
  }).sort((a,b) => a.date < b.date ? -1 : 1)
      .map(i => i.item)
}

const yearMonthDaySort = array => {
  return array.filter(item => item.year && item.month && item.day).map(item => { 
    return {
      item,
      date: new Date(parseInt(item.year),item.month - 1,parseInt(item.day))
    }
  }).sort((a,b) => a.date < b.date ? -1 : 1)
      .map(i => i.item)
}


const sortedResults = yearSort(array)
                .concat(yearMonthSort(array))
                  .concat(yearMonthDaySort(array))

console.log({ sortedResults });

Answer №2

When creating a sort compare function, start by checking the year; if they are the same, then check the month, and finally, the day.

  1. Convert all values to numbers and then compare them.
  2. An empty string will be converted to 0 when using the + operator.

const array = [
  { year: "1938", month: "6", day: "3" },
  { year: "1935", month: "5", day: "3" },
  { year: "1935", month: "", day: "" },
  { year: "1935", month: "5", day: "" },
  { year: "1934", month: "3", day: "" },
  { year: "1934", month: "3", day: "15" },
  { year: "1934", month: "", day: "" },
];

array.sort((a, b) => {
  if (a.year === b.year) {
    if (a.month === b.month) {
      return +a.day - +b.day;
    }
    return +a.month - +b.month;
  }
  return +a.year - +b.year;
});

console.log(array);

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

Explore various queries and paths within MongoDB Atlas Search

I am currently working on developing an API that can return search results based on multiple parameters. So far, I have been able to successfully query one parameter. For example, here is a sample URL: http://localhost:3000/api/search?term=javascript& ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

The simplest way to increase the size of a child element in order to generate a scrollable area

When working with HTML, it's important to consider how the size of a child div affects the parent div. If the child div is larger than its parent, scrollbars will appear on the parent div if the appropriate style rules are set. However, I'm inte ...

Create a cookie in javascript

There seems to be an issue with this code snippet: function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRc ...

The JavaScript Discord Bot is having trouble connecting to a voice channel

I'm currently working on developing a discord bot using node.js. While I've successfully set it up to respond, I'm facing an issue with summoning it to a voice channel. Here is the snippet of code I am working with: switch (args[0]) { c ...

Encountering the error message ERR_CONNECTION_TIMED_OUT while using Vue CLI

Currently, I am venturing into the world of Vuex and attempting to incorporate some API requests using this state management pattern. Here is the structure I have set up: Component.Vue export default { created() { this.$store.dispatch('getDat ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Activate a spinner when a button is clicked within a row of an antd table

I created a table with a column that includes a button like the one below: const columns = [ ... { title: "button", dataIndex: "key", render: (text, record) => { return ( <Button icon={<Del ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

"Although disabled, input elements can still be focused on in Firefox browser

Illustrative example let userInput = document.createElement("input"); userInput.id = "user-input"; userInput.type = "number"; userInput.className = "user-number-input"; userInput.disabled = true; document.body.appendChild(userInput); .number-inp ...

Adjusting iframe height based on its source URL using JQuery

Currently, I have implemented a script to adjust the height of YouTube iframes in order to maintain a 16:9 aspect ratio while keeping the width at 100% of the container. The challenge I am facing is ensuring that the script only affects YouTube videos and ...

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...

What is the technique to enable this div to be clickable?

I am trying to make each "card" of a WordPress plugin clickable on my website. I have inserted a Pure JS element with the following code: document.getElementsByClassName('fc_card-container').onclick = function() {alert('It works!');} ...

Acquiring the root URL with the $location service in AngularJS

I am facing a situation where I have a specific URL structure like the one shown below. http://localhost:8080/test#/users/list Upon further investigation, I discovered the following information: $location.url() returns -> "users/list" $location.path( ...

How can I switch the visibility of two A HREF elements by clicking on one of them?

Let me break it down for you in the simplest way possible. First off, there's this <a href="#" id="PAUSE" class="tubular-pause">Pause</a> and then we have a second one <a href="#" id="PLAY" class="tubular-play">Play</a> Al ...

Enhance the list visualization in Next.js by efficiently transferring data from child components

In my Next.js Page component, I have a setup similar to the following: export default function Index({ containers }) { const [containerListState, setContainerListState] = useState(containers); const updateContainerList = (container) => { contai ...

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

Tips for utilizing the form.checkValidity() method in HTML:

While delving into the source code of a website utilizing MVC architecture, I encountered some difficulties comprehending it fully. Here is a snippet of the view's code: function submitForm (action) { var forms = document.getElementById('form& ...

Exploring data elements using iteration in JavaScript

Here is some code that is functioning properly: Morris.Bar({ element: 'barchart', axes: true, data: [ json.bar.bar1 ], xkey: 'x', ykeys: ['y', 'z', ' ...