Sorting an array of strings that contain years in JavaScript

I am attempting to organize an array of seasons based on season and year, all while eliminating any duplicate seasons. Merely sorting the array did not produce the desired outcome, so I believe utilizing a regex might solve the issue.

const myStringArray = ["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"]
     
console.log(_.uniq(myStringArray).sort(function(a, b) {
    return b - a;                                  
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №1

If you want to achieve this, you can follow the code snippet below:

const monthsArray = ["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"]

console.log(_.uniq(monthsArray).sort(function(a, b) {
  return b.split(' ')[1] - a.split(' ')[1] || a.localeCompare(b);
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №2

To organize by year, you can use the index of a specified array to arrange seasons in order. To ensure uniqueness within the array, employ a new Set.

const myStringArray = [...new Set(["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"])];
const order = ['Winter', 'Summer', 'Fall', 'Spring'];

myStringArray.sort((a, b) => {
  let s = b.split(/\s/);
  let s1 = a.split(/\s/);
  return Number(s1[1]) - Number(s[1]) || order.indexOf(s[0]) * -1;
});

console.log(myStringArray);

Answer №3

If your strings will always be in the format <Season YY> and digits occur only once, you can easily organize them in descending order using a straightforward regex approach:

const myStringArray = ["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"]
     
console.log(_.uniq(myStringArray).sort(function(a, b) {
    return +b.match(/\d+/)[0] - +a.match(/\d+/)[0];                                  
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

The jQuery closest selector seems to be malfunctioning when trying to scroll and focus on a specific class

My HTML code snippet is as follows: <div class="main"> <div class="sub-1"> <select> <option>1</option> <option>2</option> </select> </div> <div class="sub-2"> ...

The npm audit tool uncovers unexpected dependencies in your project

When running npm audit, I receive warnings along with strange dependencies in the form of random hexadecimal strings. These strings change every time I run npm audit and are the same for all packages mentioned in the audit report. How can I remove these o ...

Six Material-UI TextFields sharing a single label

Is there a way to create 6 MUI TextField components for entering 6 numbers separated by dots, all enclosed within one common label 'Code Number' inside a single FormControl? The issue here is that the label currently appears only in the first tex ...

Learning how to utilize localStorage in conjunction with a color picker to modify the --var of :root

After spending an entire afternoon on my JavaScript issue as a beginner, I have a specific goal in mind: allowing the user to select and change the main color of the page. To implement this, I inserted a color picker in my HTML: <input type="color ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

React.js, encountering unusual behavior while implementing a timer

I'm currently working on a React project to create a basic timer. The start button should initialize the timer, while the stop button should pause it. However, I've encountered some unexpected behavior. When I click on start for the first time, ...

Tips for assigning an event to a variable in JavaScript

Here is my javascript code snippet: function drag(ev){ var x= ev.dataTransfer.setData("Text",ev.target.id); } I am trying to pass a variable within this event so that I can perform a specific action. However, the current implementation is not worki ...

Tips for effectively utilizing the ajax() function within JQuery

Within my javascript file, the following code is present: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> $.ajax({ type: 'post&apo ...

Ways to insert data into a JavaScript array using PHP

I am trying to create a form that adds products to the cart: <form method="post" > <input type="hidden" value="<?php echo $product['id']?>" id="productId" name="productId"> <input type="hidden" value="<?php echo $ ...

Dynamically format logs using Express.js Morgan

Trying to modify morgan's logging format during runtime of the application. The formatting should be based on a remote value stored in a database, where different values correspond to different morgan output formats. For example, if the database valu ...

Creating a new event using 'build' versus creating a custom event with the same name 'build'

While browsing the MDN page on Creating and Triggering Events, I came across an example showcasing the creation of events using Event or CustomEvent. The article mentions that CustomEvent allows for custom details, but doesn't elaborate much on the di ...

Master the ins and outs of working with Angular and Webpack on

Encountering issues with the webpack-angular tutorial from egghead.io during the "ES6 with Babel" step. Requesting assistance in resolving the problem. Stuck at this specific step while following the tutorial: Error message in Chrome devTools: ........ ...

Error encountered during the execution of the store method in Ajax CRUD operation

Greetings, I'm encountering an error in my AJAX code every time I try to execute the store function https://i.sstatic.net/SW86I.jpg Below is my controller: public function store_batch(Request $request) { $rules = array( 'batch_name& ...

What is the best method for eliminating a specific line from numerous HTML pages?

I have a series of HTML pages, each with a line at the top that reads: <?xml version="1.0" encoding="UTF-8" ?> When I was working on localhost, the pages opened without any issue. However, now that I have uploaded the files to the server, I am enco ...

Processing of hierarchical JSON structure

I have a JSON array that I am trying to duplicate only once while keeping it unique. Here is the code I have attempted: return_data = {}; return_data.planner = [{ "date": "2019-08-30T12:10:08.000Z", "event": [{ "name": "Event 1", "col ...

Encountered an error with the post request in expess.js: TypeError - Unable to access the property 'fullName' as it is undefined

Hey everyone, I'm new to Express and having trouble posting data from Postman. The error message I'm getting is "TypeError: Cannot read property 'fullName' of undefined". Does anyone have any suggestions on how to fix this? Thank you! ...

Selecting JavaScript Libraries During the Development of a Web Application

Transitioning from PHP & Java/Android development to web app development can feel overwhelming, especially with the abundance of Javascript Frameworks available. Check out this comparison of popular JavaScript frameworks View a list of the top JavaSc ...

What is the best way to enable click functionality on the SVG Object and smoothly scroll to anchor using jQuery?

My SVG is embedded using an object tag and includes CSS3 hover animations. However, I am facing issues when trying to hyperlink the SVG with hover animation as it interferes with clicking actions. I chose not to use the long SVG path code for better code o ...

VS Code lacks autocomplete intellisense for Cypress

I am currently using Cypress version 12.17.1 on VS Code within the Windows 10 operating system. My goal is to write Cypress code in Visual Studio Code, but encountered an issue where the cypress commands that start with cy are not appearing as auto-comple ...

The process of sending an array of objects to a Controller Action through a jQuery ajax request in .NET Core 2.2 fails to function as intended

When I stringify an array of objects, the controller action does not receive it and the parameter of the action (the model) is null. I have explored various solutions to this issue on StackOverflow, but none of them have resolved my problem. Here are the ...