What is the purpose of sorting an object using the sequence defined in an array?

Have you ever wondered how the sortWeekFunction function can rearrange an object based on a predefined array order? It may seem complex at first glance, but let's break down how this code actually works.

const weeksArr = ['sunday', 'monday', 'wednesday', 'thursday', 'friday'];

const weeksObj = {
  wednesday: 'wednesday',
  friday: 'friday',
  monday: 'monday',
  thursday: 'thursday',
  sunday: 'sunday',
};

const sortWeekFunction = (array, object) => {
  const newMapSortObj = new Map(Object.entries(object));
  const sortObj = Array.from(newMapSortObj)?.sort(
    (a, b) => array.indexOf(a[0]) - array.indexOf(b[0])
  );
  return Object.fromEntries(sortObj);
};

console.log(sortWeekFunction(weeksArr, weeksObj))
// {
//     sunday: 'sunday',
//     monday: 'monday',
//     wednesday: 'wednesday',
//     thursday: 'thursday',
//     friday: 'friday',
// }

Answer №1

"Arranging an object" may be a more accurate way to describe the process you are explaining. In most cases, the order of keys in an object is not essential. Objects, as well as Maps and Dictionaries, are not ideal for storing collections in a sorted manner. It is recommended to use an array for this purpose, or use a method like

Array.from(Object.keys(obj)).sort()
if you need to sort the keys of an object obj.

In order to understand why the code functions as it does, we need to analyze the sortWeekFunction function.

const sortWeekFunction = (array, object) => {
  const newMapSortObj = new Map(Object.entries(object));
  const sortObj = Array.from(newMapSortObj)?.sort(
    (a, b) => array.indexOf(a[0]) - array.indexOf(b[0])
  );
  return Object.fromEntries(sortObj);
};

Initially, a Map is created from the object's entries. A map is similar to a JavaScript Object, but with some variations. The map is used in the array creation process here:

Array.from(newMapSortObj)

The resulting array will look like this:

[
  [ 'wednesday', 'wednesday' ],
  [ 'friday', 'friday' ],
  [ 'monday', 'monday' ],
  [ 'thursday', 'thursday' ],
  [ 'sunday', 'sunday' ]
]

It's important to note that this is an "array of arrays."

Next, the array's .sort() method is used with a custom sorting function, defined as a lambda expression here:

sort(
    (a, b) => array.indexOf(a[0]) - array.indexOf(b[0])
  );

This process essentially compares pairs of elements in the array by evaluating

array.indexOf(a[0]) - array.indexOf(b[0])
. For instance, if a[0] is wednesday and b[0] is
sunday</code, their corresponding indexes from your provided sortArray are compared to determine their order.
</p>
<p>Finally, an object is created from the sorted array entries using <code>Object.fromEntries(sortObj)
and returned.

The end result is an object with keys that are sorted according to the specified criteria.

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 UI Sortable functions are being triggered at lightning speed

I am currently working on a project where users can create a seating chart, add rows and tables, and move the tables between different rows. The functionality for adding rows and moving tables already exists in the code. However, I am facing an issue where ...

Unable to retrieve custom CSS and JS files hosted on the server

Encountering Server Issue My server is returning a 404 NOT FOUND error when trying to access my static files: css and js. In IntelliJ IDEA, the path appears correct as shown in the image https://i.stack.imgur.com/nTFv9.png. However, upon accessing the pa ...

Customizing the appearance and dimensions of JWPlayer Audio Player with percentage-based styling

I'm currently attempting to set up an audio embed using JWPlayer, following the instructions provided in this particular article. The article suggests setting it up with the following code: <div id="myElement">Loading the player...</div> ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...

What's the best way to pass parameters through Higher-Order Components in React?

my custom component App import React, { Component } from "react"; import City from "./City"; import withDataLoader from "./withDataLoader"; const MyApp = () => { const MyCity = withDataLoader( City, "https://5e5cf5eb97d2ea0014796f01.mockapi ...

focusing on a specialized format using the serialize() method

Following up on my previous question which was answered so promptly by Meder, there is now an additional query that has arisen while creating a reusable jQuery form submission without redirecting the user. Issue The jQuery serialize() function is applyin ...

Update the input type on the fly

Hey there, I've got a bit of an unusual question. I'm looking to create a form with fields that vary for each user, like a text input or a checkbox. I attempted using Angular to achieve this: <div ng-controller="myCtrl" ng-repeat="x in prova" ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

The synergy between Object.prototype and the bind() method

Currently, I am delving into ngInfiniteScroll while being a novice in JavaScript. Upon reviewing the demo of ngInfiniteScroll, I find it quite challenging to comprehend why Reddit.nextPage has been altered to Reddit.prototype.nextPage, and how the bind() m ...

JavaScript - Combine objects by summing values with matching keys

Below is the given array : [ { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": "Pen", "Quantity": "1120" }, { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": " ...

The Fusion of JavaScript Frameworks

Is it considered poor practice for a seasoned developer to build a web application using multiple JS frameworks? For instance, when incorporating AngularJS into a project, and certain tasks could be more efficiently achieved with JQuery, should one opt fo ...

Executing a Node.js script using an absolute path

In the process of developing a basic app using Node.js and Express, I've encountered an issue. The script is located at path/to/script/server.js. When I run this script with node server.js while in the correct directory, everything functions correctly ...

Implementing a restricted Mongoose promise loop iteration count

Currently, I am developing an online store using Node, Express, and Mongoose. In the postCheckout Controller, which is responsible for handling user purchases, I am facing an issue. When a user buys a product with a quantity of 5, the code should check i ...

What is the process for combining two arrays and adding up the values of matching keys?

I need help figuring out how to merge arrays based on certain conditions. Specifically, if the keys of two arrays match, I want to add their values together, and if they don't match, I want to keep the existing value. Here are the arrays I'm wor ...

Utilizing ng-repeat to fetch and display an array of objects stored in Firebase

I am currently facing an issue while trying to access a list of notes from Firebase using AngularJS. I am unable to display the retrieved data even though there are no error messages appearing in the console. Notes.controller('ListGroupCtrl', ...

AngularJS: Retrieve individual objects from an array and subsequently initiate asynchronous requests

I am working with two tables, Category and Products, linked by a 1-N cardinality relationship. https://i.sstatic.net/e6C2y.png My goal is to retrieve all products belonging to a specific category. https://i.sstatic.net/yDrjr.png Here is the HTML table ...

Master the art of directing your attention to a list element with ease using the tab function and jQuery

I've been tasked with creating a questionnaire for a client. They want the current active question to be displayed at 100% opacity, while the inactive questions should be at 20% opacity. Currently, when the page loads, all questions are dimmed to 20% ...

Exploring the potential of Angular JS and gapi in building a seamless routed

I'm facing a similar challenge as described in this question. However, the key difference is that I require two controllers for two distinct routes, essentially representing two different tables: ../table1 and ../table2. Each table needs to fetch data ...

Enhance Shipping Options on Your Woocommerce Cart

I am facing a challenge with providing delivery options for three different countries in my e-commerce store. I want the customer to be able to select their country and instantly see the available delivery methods without having to refresh the entire page ...

Divs animated with jQuery keep on moving even after the animation has finished

My current project involves animating a single circle that scales, collides with two nearby circles, and then causes those circles to animate to specific positions. While everything works as expected, there is an issue where the two circles involved in the ...