Arrange an array of objects to a specific sequence

I am currently working with an array of objects that contain a property named 'CODE'.

[
  {
   ID: 168,
   NAME: "First name",
   CODE: "AD"
  },
  {
   ID: 167,
   NAME: "Second name",
   CODE: "CC"
  },
  {
   ID: 169,
   NAME: "Third name",
   CODE: "CCM"
  },
  {
   ID: 170,
   NAME: "Fourth name",
   CODE: "CR"
  },
]

My question is, how can I sort this array based on a customized order such as:

var item_order = ["CCM","CR","AD","CC"];

I have attempted different methods but so far without any success. Any assistance would be greatly appreciated.

Answer №1

If you want to organize an array based on a specific order, you can utilize the sort function in conjunction with indexOf.

var array = [  {   ID: 168,   NAME: "First name",   CODE: "AD"  },  {   ID: 167,   NAME: "Second name",   CODE: "CC"  },  {   ID: 169,   NAME: "Third name",   CODE: "CCM"  },  {   ID: 170,   NAME: "Fourth name",   CODE: "CR"  }],
    item_order = ["CCM","CR","AD","CC"];

array.sort((a, b) => item_order.indexOf(a.CODE) - item_order.indexOf(b.CODE));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you're dealing with large arrays, it's recommended to utilize an object for the indices.

var array = [{ ID: 168, NAME: "First name", CODE: "AD" }, { ID: 167, NAME: "Second name", CODE: "CC" }, { ID: 169, NAME: "Third name", CODE: "CCM" }, { ID: 170, NAME: "Fourth name", CODE: "CR" }],
    item_order = ["CCM", "CR", "AD", "CC"],
    order = item_order.reduce((r, k, v) => Object.assign(r, { [k]: v }), {});

array.sort((a, b) => order[a.CODE] - order[b.CODE]);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

For situations where you find yourself needing to perform this kind of operation frequently, it may be beneficial to create a small utility function to assist:

const array = [{ ID: 168, NAME: "First name", CODE: "AD" }, { ID: 167, NAME: "Second name", CODE: "CC" }, { ID: 169, NAME: "Third name", CODE: "CCM" }, { ID: 170, NAME: "Fourth name", CODE: "CR" },{ ID: 166, NAME: "Fifth name", CODE: "CCM" }, { ID: 171, NAME: "Sixth name", CODE: "XXX" }, { ID: 172, NAME: "Seventh name", CODE: "CR" }]

const sortOn = (prop, list) => {
  const order = list.reduce((obj, key, idx) => Object.assign(obj, { [key]: idx + 1}), {});
  const getVal = item => order[item[prop]] || Infinity
  
  return (a, b) => getVal(a) - getVal(b)
}

array.sort(sortOn('CODE', ["CCM", "CR", "AD", "CC"]))
console.log(array)

The approach used in the order object aligns with Nina Scholz's suggestion. The decision to add 1 to idx instead of using just idx is aimed at simplifying the subsequent line of code. By employing Infinity, items with undefined or non-matching key values are positioned towards the end during sorting. To place these items at the beginning instead, consider using 0 or -Infinity.

Answer №4

To implement custom sorting of an array, you can utilize the array.sort(customSort) method with the following custom sort function:

function customSort(a,b)
{
    a = item_order.indexOf(a.CODE);
    b = item_order.indexOf(b.CODE);

    return a - b;
}

Answer №5

var data = [
  {
   ID: 168,
   NAME: "First name",
   CODE: "AD"
  },
  {
   ID: 167,
   NAME: "Second name",
   CODE: "CC"
  },
  {
   ID: 169,
   NAME: "Third name",
   CODE: "CCM"
  },
  {
   ID: 170,
   NAME: "Fourth name",
   CODE: "CR"
  },
];

var sortOrder =  ["CCM","CR","AD","CC"];

var arrangedData = data.sort((a, b) => sortOrder.indexOf(a.CODE) - sortOrder.indexOf(b.CODE));

console.log(arrangedData);

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

Converting a JavaScript array to a PHP array using POST request

In my JavaScript script, I have the following code: cats = []; cats.push(cat1); cats.push(cat2); $.post( URL+"/edit-article.php", { id: artId, title: "PZujF0 wxKLCW", content: "ILEn3o oU9Ft6oU5", author: author, cat_id: cats } ).done(function( data2 ) ...

The Codeigniter ajax call fails to function properly when an external JavaScript file is incorporated

Why does my Codeigniter ajax request work when JS is embedded internally, but not when I try to use it as an external JS file? View the code for the sample_ajax below: <html> <head> <title></title> <scrip ...

Extract the color from the most prominent element in the viewport

I'm working on a button that will take the user to the bottom of the page, and I want the background color of the button to match the color of the first element that touches the viewport. The button is functioning properly, but I'm having trouble ...

What is a more efficient method for incorporating optional values into an object?

Currently, I am utilizing the optional addition feature in this way: ...(!!providerId && { providerId }), ...(!!practiceId && { practiceId }), Is there a more elegant shorthand method to replace this logic, such as: yield createRemark ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Adjust the CSS for the "a" tag's "title" attribute

I am using jquery.fancybox to create an image modal on my website. I have noticed that I can add a description using the title attribute. However, when the description is too long, the text is displayed on a single line and some of it disappears. How can ...

Having trouble accessing properties within a JavaScript object array in React.js?

I have a React.js component that fetches its initial state data from an API call in the componentDidMount(). This data comprises an array of objects. While I can see the entire array and individual elements using JSON.stringify (for debugging purposes), a ...

"Using Angular, when $event is triggered on multiple child elements, each child

I am facing an issue with my html element in the application: .html <a (click)="onOpen($event)"> <i class="fa fa-file-text-o"></i> <p>Profile</p> </a> .ts onOpen(event):void { console.log( event.target ) ...

Error message: Incorrect XMP data detected within PhotoSphereViewer" and "WebGL issue: INVALID_VALUE error when attempting to load faulty image data

I'm currently utilizing Photo Sphere Viewer to showcase a panoramic image similar to how Facebook does it, but I am encountering some difficulties. Below is the code snippet: <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/em ...

Accessing variable from JavaScript function in Python App Engine

Embarking on my first journey into the world of web technologies, I find myself tangled in a dilemma. Currently immersed in my initial appengine project, I am attempting to manipulate a value generated within a JS function (embedded in my .html file) using ...

Validating email addresses individually

I am currently working on implementing form validation for an email field with specific requirements. The validation process includes: Checking if an email has been entered by utilizing the required attribute and displaying a message if no email has been ...

What is the best way to iterate through an array of objects in React and JavaScript, adding a new property to each object in order to generate a new array

Greetings, I am currently dealing with an array of objects structured as follows: const arr_obj = [ { children: [{}], type: "type1", updated: "somevalue", }, { children: [{}], type: ...

Populate your website with both a Bootstrap Popover and Modal for interactive user engagement through hover

Here's the situation: I want to showcase a user's name with a popover that reveals a snippet of their profile information. I've got that part down, where it dynamically generates and displays the popover content as needed. The popover functi ...

Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this: <div id="one">content</div> <div id="two">content</div> These elements are followed by another set of elements (without any parent, placed directly after th ...

How to Use a PHP Variable in an External JavaScript File

After going through multiple discussions on this platform, I am still facing challenges in passing a variable from PHP to an external JS file. Can anyone offer some help? This is what I have in my PHP file; <script type="text/javascript"> var pass_ ...

Utilize jQuery to dynamically assign classes to list items within a unordered list based on the length of an array

HTML: <ul class="tickboxes"> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i>< ...

Utilizing a combination of PHP and jQuery, certain checkbox options were dynamically deactivated

<input type="checkbox" name="pref[]" value="red//fuji" />Fuji <input type="checkbox" name="pref[]" value="red//pinklady" />Pink Lady <input type="checkbox" name="pref[]" value="red//reddelicious" />Red Delicious <input type="checkbox" ...

Obtain the Upload URL using an Angular service

I am currently working on an Angular project that uses Dropzone.js as the drag-and-drop file upload component. The challenge I'm facing is that Azure requires a unique URL to be generated for each file upload. Dropzone.js has a "url" config option th ...

Unveiling the enigma of Array.from()

Can anyone provide an explanation for this? Array.from(undefined); // Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) Array.from(null); // Uncaught TypeError: object null is not iterable (cannot read property S ...

Tips for incorporating a last or recently visited feature similar to Google Docs using MongoDB

Within my database, I have two collections: users and projects. These collections share a many-to-many relationship. One user can be associated with multiple projects and one project can be assigned to multiple users. In the user object, I store an array o ...