Objects in the array are failing to sort in the expected sequence

I am facing an issue with sorting an array of objects by a date property using the lodash function orderBy. I have tried to sort it in both ascending and descending order.

var searchObj = [{id: 1, postDate: '2/24/2016 5:08 PM'},
                 {id: 2, postDate: '3/14/2012 8:39 AM'},
                 {id: 3, postDate: '3/23/2016 1:56 AM'},
                 {id: 4, postDate: '5/9/2016 8:14 AM'},
                 {id: 5, postDate: '11/11/2016 05:26 PM'},
                 {id: 6, postDate: '05/19/2016 03:40 AM'},
                 {id: 7, postDate: '5/10/2016 9:23 PM'},
                 {id: 8, postDate: '11/07/2017 01:07 PM'},
                 {id: 9, postDate: '6/7/2011 9:20 AM'},
                 {id: 10, postDate: '11/03/2015 12:03 PM'}];

console.log(searchObj);

searchObj = _.orderBy(searchObj, [obj =>
  new Date(obj['postDate'].trim()).getTime() / 10000
], ['asc']);

console.log(searchObj);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b9bab1b4a6bd95e1fbe4e2fbe1">[email protected]</a>/lodash.min.js"></script>

However, the sorted array is not always correct, resulting in mixed up dates like:

  1. 2/24/2016 5:08 PM
  2. 3/14/2012 8:39 AM
  3. 3/23/2016 1:56 AM
  4. 5/9/216 8:14 AM
  5. 5/10/2016 9:23 PM
  6. 6/7/2011 9:20 AM

Does anyone have any suggestions on how to fix this sorting issue?

Answer №1

One problem arises from the fact that the strings you are using are not in the correct format for parsing with new Date, as specified in the ECMA 262 standard. When this happens, implementations may resort to "...any implementation-specific heuristics or implementation-specific date formats..." — which could lead to varied interpretations of the same string inputs, despite them all being intended to be in the same format.

To avoid this issue, it is recommended to manually parse your strings and utilize the

new Date(year, month, day, hour, minute, sec, ms)
constructor instead. (The process is straightforward and there are plenty of examples available on platforms like Stack Overflow.)

Answer №2

Is lodash really necessary? The truth is, you can live without it.

function sortListByDate(inputList, dateProperty, isDescending){
  let result = inputList.sort(function(item1, item2){
    return item1[dateProperty].getTime() - item2[dateProperty].getTime();
  });
  if(isDescending){
    return result.reverse();
  } else {
    return result;
  }
}

Remember, the 'isDescending' parameter should be true for ascending and false for descending sorting.

Check out an example here: https://jsfiddle.net/yourusername/examplelink/

Answer №3

Great job, you're almost there! Just remember to remove the [] from the second parameter in _.orderBy.

var searchObj = [{id: 1, postDate: '2/24/2016 5:08 PM'},
                 {id: 2, postDate: '3/14/2012 8:39 AM'},
                 {id: 3, postDate: '3/23/2016 1:56 AM'},
                 {id: 4, postDate: '5/9/2016 8:14 AM'},
                 {id: 5, postDate: '11/11/2016 05:26 PM'},
                 {id: 6, postDate: '05/19/2016 03:40 AM'},
                 {id: 7, postDate: '5/10/2016 9:23 PM'},
                 {id: 8, postDate: '11/07/2017 01:07 PM'},
                 {id: 9, postDate: '6/7/2011 9:20 AM'},
                 {id: 10, postDate: '11/03/2015 12:03 PM'}];

console.log(searchObj);

searchObj = _.orderBy(searchObj, obj =>
  new Date(obj['postDate'].trim()).getTime() / 10000
, 'asc');

console.log(searchObj);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="076b686366746f47332936302933">[email protected]</a>/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

Using JSON files in React applications is essential for accessing and displaying static data. Let's

If I want to refer to a file locally in my JS code instead of on a remote server, how can I do that? I know the file needs to be in the public folder, but I'm unsure how to reference it in the JavaScript provided above. class App extends Component { c ...

What is the method for determining someone's age?

I am trying to extract the date from a field called "DatePicker" and then enter that date into the field labeled "NumericTextBox" Thank you <div> <sq8:DatePicker runat="server" ID="dateDatePicker"> <ClientEvents OnDateSelected="get_curr ...

The autocomplete feature in Google Maps is not functioning properly when used within a modal

I've integrated the Google Maps API to enable autocomplete address functionality for an input box on my page. However, I'm encountering an issue where everything works fine on the page itself, but it doesn't work when the input box is placed ...

Can you explain the purpose of using the 'apply' method in this particular implementation of memoization in JavaScript?

_.memoize = function(func) { var cache = []; return function(n){ if(cache[n]){ return cache[n]; } cache[n] = func.apply(this,arguments); return cache[n]; } }; I'm curious about the usage of 'this' in func.appl ...

How can a static website incorporate a local image without the need for backend functionality?

I have a unique challenge with my static website. It is designed to display a local image from the user's computer without utilizing a traditional backend system. The website itself is hosted on a static file server, and all image processing must be d ...

The table fails to refresh after adding, modifying, or removing a row

Incorporating ReactJs with Material-UI, I am working on displaying a table of Car components where the display does not update after any Create, Edit, or Delete action has been performed. Below is the structure: class MainCar extends React.Component { c ...

Encountered an error while trying to update information in Angular

I have been working on a project involving a .NET Core Web API and Angular 11 (Full-Stack) project. I have successfully managed to add data to the database in my back-end, but I am encountering an issue when trying to update the data. Below is a snippet o ...

Utilize the double parsing of JSON information (or opt for an alternative technique for dividing the data

Looking for the most effective approach to breaking down a large data object retrieved from AJAX. When sending just one part (like paths), I typically use JSON.parse(data). However, my goal is to split the object into individual blocks first and then parse ...

The performance of Three.js is directly influenced by the quantity of objects present

Just completed a project in WebGL using Javascript and the 3D library known as three.js Unfortunately, the performance of the project is less than impressive - slow from the start with occasional moments of adequacy. In this game, there are: 1 car, 6 ora ...

Struggling with making changes to a instantiated "this" object within a pseudo javascript class

If you scroll down to the bottom of this post, you'll find a workaround or possible solution. I've been grappling with understanding how pseudo classes work together to achieve the task I'm attempting (explained in the code below). It might ...

Add items to a new array with a property set to true, if they are present in the original array

Could someone assist me with the following situation? I need an array of strings. A function is required to map the array of strings, assigning each element a name and key, while also adding another object "checked: false". Another function should take t ...

Choosing Drop Down Options Dynamically with Jquery

I have a total of 4 Drop Downs on my page. https://i.stack.imgur.com/6tHj5.png Each drop-down initially displays a "--select--" option by default. Additionally, each drop-down has a unique ID assigned to it. The second drop-down is disabled when the abov ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

A guide to declaring MongoDB models in TypeScript across multiple files

In my Node.js TypeScript project, the structure is as follows: https://i.stack.imgur.com/YgFjd.png The crucial part of the structure lies in mongoModels. I have 2 models where each Category model is connected and contains field category.expertUserIds whi ...

AngularJS - the element of surprise in execution sequence

Encountering a puzzling issue that exclusively affects Internet Explorer (any version) and not Chrome. An "items" array is stored within the "doc" object. Users have the capability to edit items, which essentially deletes the item but retains its content ...

The process of sorting through an array of objects based on their specific types in TypeScript

I am working on a function that filters an array of objects based on their type property: export const retrieveLayoutChangeActions = (data: GetOperations['included']) => data.filter(d => d.type === 'layoutChangeAction') as Layou ...

The AngularJS error message: TypeError: Unable to access the 'images' property because it is undefined

Currently using AngularJS version 1.5.11 I am attempting to present images sourced from a JSON array. Is my method correct: $scope.mainImage = $scope.template.images[0].name;. The issue arises at the line where it says it cannot read property of images. ...

How about using a JQuery variable?

I'm a beginner in jQuery and I have this code snippet that displays a div when a specific link on a map is hovered over: <div id="locationmap"> <a class="linkhide" id="link1" href="#">Occupier 1</a> <a class="linkhide" id ...

Manipulate elements by adding and removing classes sequentially based on an array

Previously, some had difficulty understanding my question. I have an array of variables representing the ids of 5 divs. My goal is to change the color of each div sequentially for a brief moment before reverting back, mimicking the behavior of traffic ligh ...

Discover and analyze quantities across various columns in Excel when certain criteria are fulfilled

Within my data table, each row represents a client and every month I add a new column to indicate the type of orders they placed (A, B, or C). I am seeking to pinpoint clients who have made an order of type A at any point and then later switched to making ...