Tips on arranging an array based on dates and data in JavaScript?

I have an array with dates and other data that I need to sort based on the dates. I'm unsure of how to go about this. Can someone please assist me?

Here is the array in question:

0:{_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: 0, Unfollowcount: 116}
1:{_id: "27-10-2017", CommentCount: 235, Likecount: 495, Followcount: 802, Unfollowcount: 98}
2:{_id: "28-10-2017", CommentCount: 232, Likecount: 52, Followcount: 0, Unfollowcount: 799}
3:{_id: "29-10-2017", CommentCount: 236, Likecount: 52, Followcount: 0, Unfollowcount: 611}
4:{_id: "30-10-2017", CommentCount: 233, Likecount: 58, Followcount: 0,  Unfollowcount: 0}
5:{_id: "31-10-2017", CommentCount: 240, Likecount: 175, Followcount: 0, Unfollowcount: 0}

Desired output:

0:{_id: "27-10-2017", CommentCount: 235, Likecount: 495, Followcount: 802, Unfollowcount: 98}
1:{_id: "28-10-2017", CommentCount: 232, Likecount: 52, Followcount: 0, Unfollowcount: 799}
2:{_id: "29-10-2017", CommentCount: 236, Likecount: 52, Followcount: 0, Unfollowcount: 611}
3:{_id: "30-10-2017", CommentCount: 233, Likecount: 58, Followcount: 0, Unfollowcount: 0}
4:{_id: "31-10-2017", CommentCount: 240, Likecount: 175, Followcount: 0, Unfollowcount: 0}
5:{_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: 0, Unfollowcount: 116}

Answer №1

To start, you must convert the date-string into an actual Date object. Once this is done, you can customize the sorting as needed:

const inputs = [
  {_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: 0, Unfollowcount: 116},
  {_id: "27-10-2017", CommentCount: 235, Likecount: 495, Followcount: 802, Unfollowcount: 98},
  {_id: "28-10-2017", CommentCount: 232, Likecount: 52, Followcount: 0, Unfollowcount: 799},
  {_id: "29-10-2017", CommentCount: 236, Likecount: 52, Followcount: 0, Unfollowcount: 611},
  {_id: "30-10-2017", CommentCount: 233, Likecount: 58, Followcount: 0,  Unfollowcount: 0},
  {_id: "31-10-2017", CommentCount: 240, Likecount: 175, Followcount: 0, Unfollowcount: 0}
];

const results = inputs.sort((a, b) => getDate(a._id) - getDate(b._id));

function getDate(s) {
  const parts = s.split('-');
  return new Date(parts.pop(), parts.pop() - 1, parts.pop());
}

console.log(results);

Keep in mind that this solution is only compatible with modern browsers due to the use of Arrow function.

For additional information, you can check out Arrow functions and perhaps Array pop

Answer №2

Your date formatting is not compatible with JavaScript, so it is necessary to reverse it prior to passing it to the Date constructor for comparison.

console.log(arr.sort(function(a,b) {
    return new Date(a._id.split('-').reverse().join('-')).getTime() - new Date(b._id.split('-').reverse().join('-')).getTime()
}))

Following this approach will resolve the issue.

Answer №3

To achieve the desired result, you can implement the following code snippet:

my_array.sort(function(a, b) { 
    return new Date(a._id.split("-").reverse().join("-")).getTime() - new Date(b._id.split("-").reverse().join("-")).getTime(); 
});

Explanation of the sort function:

This function is optional and allows for defining an alternative sorting order. It should return a negative, zero, or positive value based on the arguments, for example: function(a, b) { return a - b; } When the sort() method compares two values, it uses the compare function to determine the sorting order based on the returned value (negative, zero, positive).

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

Revolutionizing Form Select Field: Introducing Rails' Dynamic Input Rendering

I'm a beginner in coding, so please bear with me if my question sounds amateurish. Currently, I am developing an e-commerce website where customers can order posters from images uploaded to the site. They should be able to choose the size of the poste ...

Difficulty with linking a CSS property to an HTML element using JavaScript

I'm currently working on building a custom carousel from scratch. Instead of using pre-made code snippets, I decided to challenge myself by creating one using setTimeout in JavaScript. However, I seem to be encountering an issue that I can't quit ...

Leveraging HTML5's local storage functionality to save and manage a collection of list elements within `<ul>`

I need help with saving a to-do list in HTML so that it persists even after refreshing the browser. Can anyone assist me? html <!DOCTYPE html> <html> <head> <title>My To-Do List</title> <link rel="sty ...

"Encountering a problem with using setState in React Hook useEffect

I am currently utilizing the useState hook with two arrays: imageList and videoList. In my useEffect hook, I iterate through the data using forEach method. If the type of the item is an image, it should be pushed to the imageList array. However, after exec ...

What is the process for obtaining the Tag from a React Component?

Not the HTML DOM element tag, the JSX tag, the react class name. As I work on creating an editor, adding items to the canvas array requires me to check and call the appropriate method based on what is being added. A simplified version of my idea: changeS ...

Bringing information from MSSQL database into a two-dimensional array

I am currently developing a web application to generate a trial balance report. Although the app successfully prints the description, it does not format it in a line by line manner. I have attempted to use the .filter function but I am unsure of how to ap ...

What are the steps to build a dynamic webpage in a Django project?

For my Django app, I have successfully created static pages without any ajax requests. However, I now want to add a dynamic subpage that can change its content without refreshing or reloading the entire page. Let me explain what I'm trying to achieve ...

What is the process for configuring socket.io to solely listen on a single designated route?

Is there a way to make socket.io listen only on my /home route, instead of every route? I tried changing the configuration but it only displayed a JSON file on the home path. const server = require('http').Server(app); const io = require('s ...

Combining query results/objects by id in an array within a React application with Firebase Firestore

After retrieving chat messages from a Firestore snapshot, I have the following query result involving conversations among three individuals: {timestamp: "October 25th 2020, 11:13:59 am", name: "John Doe", email: "<a href="/cdn ...

Retrieve only the items from a JavaScript array where the index is below a specified value

My goal is to filter out all the items from the initialItems list that have an index lower than the current item. For example, if the current item is CM, I want to display QS, IT, and AB in a draggable dropdown menu. However, I'm unsure of how to prop ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...

Use React to increment a variable by a random value until it reaches a specific threshold

I am currently working on creating a simulated loading bar, similar to the one seen on YouTube videos. My goal is for it to last 1.5 seconds, which is the average time it takes for my page to load. However, I have encountered an issue with the following co ...

Avoid receiving input for a button that is being covered by another button

I am currently developing an Idle Game and I am looking to include 'buy buttons' for purchasing buildings, along with a sell button embedded within the buy button. Just as a heads up, these buttons are represented by DIVs acting as buttons. Here ...

Understanding how to parse an array of arrays in JavaScript can be a

Looking for a function that can extract a value from an array containing multiple arrays? Simply use getValueFromArray(array, [2, 4]) to get the 4th element of the 2d array within the main array. Check out the code snippet below: function getValueFromArr ...

What causes my slider to speed up with an increase in items and slow down with fewer items in bxslider?

Find more information here jQuery('.homepage_slider').bxSlider( { minSlides: 1, maxSlides: 4, slideWidth: 200, slideMargin: 30, ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Analyzing the array information

I am in need of 4 associative arrays, each containing data for the same 4 users. Array ( [0] => Array ( [userName] => jim [count] => 6 ) [1] => Array ( [userName] => joe [count] => 6 ) [2] => Array ( [userName] => jesse [count] =&g ...

Exploring Protractor testing with Bootstrap modals

I'm having an issue testing a bootstrap modal. Here's the scenario: Click on a button to display the modal The modal body has a list of buttons When I click on one of them, it doesn't do anything My Protractor code snippet: element(by. ...

The Kenburn zoom image effect fails to function

I want to implement a zoom effect on an image using the Ken Burns effect when it is clicked. However, the code I have written does not seem to be working as expected. Here is the code snippet: $(document).ready(function () { $('.kenburns').on( ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...