Arrange a collection of items based on a specific criterion, include the sorted position within each item, and revert back to the

Let's say we have the following array:

  const array = [
    { name: 'b' },
    { name: 'a' },
    { name: 'c' },
  ]

The objective is to add a new property to each object based on its position in the sorted array:

  const array = [
    { name: 'b', sortIndex: 1 },
    { name: 'a', sortIndex: 0 },
    { name: 'c', sortIndex: 2 },
  ]

One approach is to first sort the array by name, then iterate through and assign index values as follows:

 const array = [
   { name: 'a', sortIndex: 0 },
   { name: 'b', sortIndex: 1 },
   { name: 'c', sortIndex: 2 },
 ]

However, the current solution involves multiple loops which may not be efficient. Any suggestions on how to improve this process?

export function setSortIndexes(series) {
  const clone = cloneDeep(series);
  const sorted = orderBy(clone, [
    (x) => (x.name ? x.name.toLowerCase() : null),
  ]);

  sorted.forEach((x, i) => {
    x.sortIndex = i;
  });

  series.forEach(x => {
    const index = sorted.findIndex((s) => s.name === x.name);

    if (index !== -1) {
      x.sortIndex = sorted[index].sortIndex;
    }
  });

  return series;
}

Answer №1

To properly sort the array, create a temporary array that includes the original index.
Sort the temporary array by the name field.
Then add the sorted index back to the original object in the array.

array
  .map((e, i) => ({ name: e.name, originalIndex: i }))
  .sort((a, b) => a.name.localeCompare(b.name))
  .forEach((e, i) => array[e.originalIndex].sortIndex = i)

Answer №2

Here is a method you can use:
Instead of duplicating objects (or some of its elements) in a new array, you can simply create an array of pointers to these objects.

const array = 
  [ { name: 'b'} 
  , { name: 'a'} 
  , { name: 'c'} 
  ] 
array                  // create a new array  
  .map(o=>({o}))      // of pointers ( o ) to refer each array objects
  .sort((a,b)=>a.o.name.localeCompare(b.o.name)) // sort 
  .forEach((_,i,a)=>a[i].o.sortIndex = i )      // add the sortIndex attr 


console.log(array)

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

Tips for enhancing undo/redo functionality when working with canvas drawings in React

Currently, I am working on implementing undo/redo functionality for html-canvas drawing on medical (.nii) images in a React application. The images consist of slices stored in a Uint8ClampedArray and usually have dimensions around 500 (cols) x 500 (rows) x ...

Encountering an issue with undefined this.auth.settings when implementing Firebase Phone Authentication in NextJS 14

I am facing an issue with authenticating users using the firebase OTP system. Can someone assist me with resolving the problem of 'this.auth.settings is undefined' while implementing Firebase Phone Authentication in NextJS 14? The code snippet ...

React - Issues with setTimeout() method not triggering following Promise.all execution

I am facing an issue with my arrow function that is called from the `componentDidMount` lifecycle method to fetch updated status of schedules every 20 seconds using a `setTimeout()`. The problem is that the `setTimeout()` method does not trigger another re ...

Utilizing JavaScript values instead of relying on HTML values - a step-by-step guide

I am facing a challenge with 3 buttons that I have created: <button id="b1">0</button> <button id="b2">0</button> <button id="b3">0</button> Instead of retrieving the value from the HT ...

Transferring information from an online platform onto pre-arranged sheets for hard copy

Has anyone had success printing from a website? I have some papers that are already printed with checkboxes. These checkboxes need to be filled in based on information entered through a web form or retrieved from a MySQL database. All of this information ...

Experiencing issues and alerts when handling JSON data

Here is the Json data I am attempting to represent using Json-LD : var schemaOrg = angular.toJson({ "@context": "http://schema.org", "@type": "RealEstateAgent", "RealEstateAgent": { ...

Determine the next element in the array using a foreach loop

In my Wordpress code, I am using a foreach loop to retrieve category names. $i = 0; foreach($catnamea as $legname ) { $i++; echo $legname[$i].'<br>'; } When I access $legname[0], it displays a category name, and increasing the number li ...

Trouble with Javascript slideshow: Incorrect display and malfunctioning

Struggling with implementing a slideshow banner on my webpage, despite following the W3 tutorial. Here is the code I am currently using: HTML: <div class="slide-content" style="max-width:1000px"> <img class="slidepic" src="testheadphoto.jpg" st ...

Unexpected token error in TypeScript: Syntax mistake spotted in code

Being new to Angular, I understand that mastering TypeScript is crucial for becoming a skilled Angular developer. Therefore, I created this simple program: function loge(messag){ console.log(messag); } var message:string; message = "Hi"; loge(messa ...

When a Javascript function returns true/false, it can sometimes result in undefined

Currently, I am facing an issue with my function. Utilizing a MongoDB Database to validate if something exists, the objective is to return false when a data value is true and false otherwise. Up until this point, everything seems to be functioning correct ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...

Navigating custom tokens between different pages

My application utilizes a custom log-in system that generates an encrypted Token to signify a user's logged-in status. This Token is then passed to another page (Dash.aspx) via the QueryString parameter. On Dash.aspx, the Token from the QueryString i ...

Issue with Datatables FixedColumns plugin in IE8/7 and Firefox

I am encountering issues with the FixedColumn plugin on IE8, IE7, and Firefox. All of them are causing my table to malfunction, displaying the following error: Error: Invalid argument. Line: 566 Char: 3 Code: 0 URI: ./resources/javascript/dataTable/Fixed ...

Can anyone tell me where to find the unminified version of Bootstrap 3's docs.min.js file?

Could someone please provide me with the original version of this file? I've been trying to search for it in the project but haven't had any luck. You can find it here: https://github.com/twbs/bootstrap/blob/master/docs/assets/js/docs.min.js. ...

AngularJS $routeProvider is experiencing difficulties with its routing functionality

I am a beginner with Angular and I'm trying to understand how multiple routes can lead to the same view/templateUrl and controller. This is what I have written: angular .module('mwsApp', [ 'ngAnimate', 'ngCookies&ap ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

Manipulate JSON data structure with JavaScript

The initial JSON data: { "data": { "count_at_hub": [ { "hub": "A", "date": "", "size": "1", "count": 141 }, { "hub": "A", "date": "", "size": " ...

Managing image downloads from a Node.js server: Tips and Best Practices

Currently, I am in the process of learning node.js and recently encountered a scenario where I need to download an image from the server by clicking a button on the webpage. I have set up an endpoint that receives two parameters: - The name of the image ...

Using ReactJS and Ruby on Rails to implement an AJAX delete request

There is a component named Items residing inside a parent component called ItemsContainer. A click on a button within the Items component triggers an Ajax function to delete that specific Item. However, I am encountering a 500 error message at the moment ...

An element generated using a JavaScript loop is covering another element in the layout

I am facing an issue with positioning images within a div to a span. The problem arises as the images are overlapping each other and I am uncertain about how to properly place each image when it is added. Below is the code snippet: The CSS: <style ty ...