Arranging a variety of array objects based on unique identifiers

Previously, I successfully combined two arrays into one and sorted them by the created_at property using the sort() method.

let result = [...item.messages, ...item.chat_messages]
result.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
item.messages = result

Now, I am faced with a new challenge. I need to incorporate another array (sms_messages) into this existing array and sort it based on its scheduled_at field.

Is there a way to achieve this using the same approach as before?

let result = [...item.messages, ...item.chat_messages, ...item.sms_messages]
// then order by messages' and chat_messages' created_at (as done previously) along with 
// sms_messages' scheduled_at

Answer №1

If you want to prioritize the `scheduled_at` property over `created_at`, you can use the logical OR (`||`) operator in JavaScript. This code snippet will sort an array of objects based on these properties:

result.sort((a, b) => 
    new Date(b.scheduled_at || b.created_at) - new Date(a.scheduled_at || a.created_at))

Answer №2

To effectively sort the objects, first identify which property exists and then utilize it for sorting.

const sortByDate = criteria => {
  return (item1, item2) => {
    let prop1 = criteria.find(c => item1.hasOwnProperty(c));
    let prop2 = criteria.find(c => item2.hasOwnProperty(c));
    if (!prop1 || !prop2) return 0;
    return new Date(item2[prop2]) - new Date(item1[prop1]);
  };
}

results.sort(sortByDate(['date_created', 'last_modified']));

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

Is there a way for me to display an alert notification when a website requests access to additional storage on my computer?

Is there a way to set up an alert notification in Internet Explorer when a website requests additional storage on your computer? The notification would ask: Do you want to grant permission for this website to use additional storage on your computer? ...

Mastering Angular: Tackling a Directive with Two Parts

I'm working on a directive that's responsible for embedding footnotes into a body of text while providing popover functionality. The text-notes directive is designed to be placed on a parent element, loading content and its related text notes dyn ...

Dynamic components in Angular and the error of ExpressionChangedAfterItHasBeenChecked

Seeking to create a versatile component that can dynamically contain various components. The objective is to compose an article with the flexibility of including either paragraphs or tweets. The following code defines DynamicArticleComponent: @Directive( ...

The app has crashed, currently waiting for any file changes before starting again

Can someone assist me? I am encountering an issue while trying to run npm start. The error pertains to the server.js file. [nodemon] restarting due to changes... [nodemon] starting `node server.js` /Users/johnngo/Desktop/LambdaSchool/HTTP-AJAX/server.js ...

The built-in functions of Wordpress are not able to be identified in the ajax PHP file

As a newcomer to Wordpress development, I am facing challenges with implementing ajax on my WordPress site. I am currently working on a plugin that requires the use of ajax. However, my php file (xxxecommerce.ajax.php) is not recognizing the built-in Word ...

Guide on extracting the ID within a for loop and incorporating it into a Vue.js function

In order to make an API request, I need to retrieve the id. However, whenever I try to include <a v-on:click="showRecipe({{inf.Id}})">Recipe</a> in my code, the entire page crashes. Removing this line resolves the issue. How can I pass the id ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

performing a regex operation on an array and saving the results in a new array

I have written a code snippet that extracts the date "2016-06-13" from the string "ffg_LTE_2016-06-13." $re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/'; $str = "ffg_LTE_2016-06-13"; preg_match($re, $str, $matches ...

The power of Numba with multi-dimensional Numpy arrays

Preliminary Setup These are the two different approaches to matrix calculation that I have: The initial method involves a matrix with dimensions (n, m) where the calculations are done in nested for-loops and repeated repetition-times: import numpy as ...

Vue.js Applications tend to encounter Expected Errors originating from JavaScript

I've been diving into learning Vue.js using Visual Studio 2017. Currently, my goal is to create applications with multiple buttons that trigger the display of a message upon being clicked. However, when I attempt to run this code, I encounter the foll ...

What is the best way to create a line graph with D3.js in order to display data that is obtained from a server-side source?

I am trying to access data from a server side link, which is as follows: The data I want to retrieve is in JSON format and looks like this: {"Id":466,"Name":"korea", "Occurren ...

Unusual issue encountered when launching an express application in node.js

Starting my app is easy with nodemon - just type nodemon However, I encountered an error when trying node app.js I have checked my package.json and it is properly configured with: "scripts": { "start": "node ./bin/www" } ...

Shift div position when clicked and employ jQuery animations

I have been attempting to add animation to a DIV element by using jQuery. The goal is to move the DIV from the center to the left when it is clicked, but I am encountering some issues. The parent div has a position of "relative", and my initial idea was to ...

How to remove the black border on a material-ui button

I am currently working with the material-ui datepicker and buttons. Whenever I click on the datepicker icon to select a date or any of the buttons, I notice a black border appearing. How can I remove this black border from the design? ...

Encountering Build Issue: "NgSemanticModule is not recognized as an NgModule" persists despite inclusion of dependencies and importing into primary module

I have posted my module, component, and package file here. I am attempting to implement a click event with ngif, but I keep encountering an error. The specific error message is "ERROR in NgSemanticModule is not an NgModule". I'm unsure if this error ...

Adding data to each span and div using JavaScript is a simple task that can be achieved easily

What is the best way to add information to each span and div element using JavaScript? $(document).on("click",".selection-state",function(){ stateid = $(this).attr("rel"); $("#my_tooltip").html(data); } e ...

I want to know how to showcase elements from a list one by one and cycle through them using a button with a nodejs server and Pug

As someone who is brand new to Web development, NodeJs servers, and Pug, this is my first time diving into any of these technologies. My goal is to create a dynamic box (in the form of a div) that changes its content based on a list from a JSON file. Initi ...

Tips for modifying jsFiddle code to function properly in a web browser

While similar questions have been asked before, I am still unable to find a solution to my specific issue. I have a functional code in jsFiddle that creates a table and allows you to select a row to color it red. Everything works perfectly fine in jsFiddle ...

Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work. In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be caus ...

Transfer a csv file from a static webpage to an S3 bucket

Looking to create a webpage for uploading csv files to an S3 bucket? I recently followed a tutorial on the AWS website that might be helpful. Check it out here. I made some modifications to accept filename parameters in my method, and everything seems to ...