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

Exploring the concept of passing variables by reference in PHP with the end

When I attempted to pass an explode statement into end() function, my IDE gave me a notice saying "Only variables can be passed by reference," which was not surprising. What puzzled me was the result when I tried: $array = ['cat', 'dog&apos ...

When redirecting to the same component, Vue.js hooks are not triggered

In my Vuejs project, I have two pages located at the same level with a common component. However, when I redirect from post/new to post/edit/:id, the beforeMount method is not being called. redirect() { this.$router.push({path: `home/post/edit/${this ...

"Unable to move past the initial segment due to an ongoing

My portfolio webpage includes a "blob" and "blur" effect inspired by this YouTube video (https://www.youtube.com/watch?v=kySGqoU7X-s&t=46s). However, I am encountering an issue where the effect is only displayed in the first section of the page. Even a ...

Why is AJAX returning false and I'm unable to figure out the reason?

My goal is to perform a database query for a keyword instantly upon input change. Currently, I am able to successfully execute the query and store all the results. However, when attempting to display the results using GET, my ajax function returns false. W ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

How can I notify a particular user using Node.js?

This is the code I have for my server in the server.js file: var socket = require( 'socket.io' ); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = sock ...

Finding the index of a row using jQuery

I am encountering an issue with the following code: $("#myTable td").each(function(){ if($(this).html()=="") { rIndex1=$(this).parent().index(); //this value remains "1" rIndex2=$(this).rowIndex; //this value stays as "undefined" Un ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

What is the method for altering the background color of an input field upon entering text?

As a beginner in Javascript and jQuery, I am struggling to understand why my code is behaving the way it does. I have written two similar functions aimed at changing the background color of an input field. The objective is to set the background color of t ...

A function that listens for the onmouseover event and updates the image source of an HTML img element

I have created a function that positions my objects based on the array they are assigned to. For example, if they are in players[0], they will be placed in one position, and if they are in players[1], they will be placed elsewhere. The X and Y values are ...

What is the process for including an optional ngModelGroup in Angular forms?

I'm encountering an issue with incorporating the optional ngModelGroup in angular forms. Although I am familiar with how to use ngModelGroup in angular forms, I am struggling to figure out a way to make it optional. I have attempted to pass false, nu ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

The GAS and Bootstrap web form is able to search for and display data in a table format. However, it lacks the functionality to display clickable links or hyperlinks directly from the spreadsheet

Check out this awesome web application https://script.google.com/macros/s/AKfycbyEHj5qtIeCZh4rR6FutBLQ3N9NihreaTv7BFj4_saOfNWJUG0Tn2OtvzQs4zASYHnNiA/exec I'm looking for help to display links or hyperlinks that some cells contain. Any suggestions? ...

Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0. var obj = ["race", "sack", &qu ...

Building a custom Vuetify extension to enhance core features

I am currently working on developing a plugin-based component library to ensure consistency across various product lines using vuetify. However, when I try to install the library and add the components, I encounter multiple errors related to the dark theme ...

The email validation UI dialog is failing to display any dialog

<html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"& ...

Lowest value malfunctioning

I have encountered an issue with setting minimum values for 4 things. All 4 things are supposed to have the same minimum value as the first thing, but when moving the slider, everything goes back to normal and works fine. Where could the problem be origina ...

Button for searching through the Bootstrap navigation bar

I'm currently working on adding a search menu to the navbar in two different designs - one for screens below 767px and another for screens above 767px. Although I have been successful in expanding the search bar, I am facing issues with the correct p ...

Enhance multiple select functionality

I am currently working on a function to dynamically update the options in a select input based on the selection made in another select input. Specifically, when Method1 is selected, I want only the options 1A, 1B, and 1C to appear in the second select. S ...

Verify the string to see if it contains a Steam game key

I am seeking assistance with a task that involves verifying whether a specific string contains a particular pattern: Below are several strings in an array: [ "please use this key: ')D9ad-98ada-jiada-8a8aa'", "kK8AD-AODK8-ADA7A", "heres a fr ...