Guide on organizing an array of objects by the sub-part of their property values

Is there a way to order the elements in the given array based on a custom criteria related to the last 3 letters of 'prop2' in descending order? The specific order should be 'ABR', 'FDE', 'ZFR'. Another array needs to be sorted with the order 'ZFR', 'FDE', 'ARB'.

Input example:

const arr = [
  { prop1: 3, prop2: '3FDE' },
  { prop1: 4, prop2: '5ZFR' },
  { prop1: 5, prop2: '7ABR' }
]

Desired output:

const arr1 = [
  { prop1: 5, prop2: '7ABR' },
  { prop1: 3, prop2: '3FDE' },
  { prop1: 4, prop2: '5ZFR' }
]

and

const arr2 = [
  { prop1: 4, prop2: '5ZFR' },
  { prop1: 3, prop2: '3FDE' },
  { prop1: 5, prop2: '7ABR' }
]

Answer №1

const arr = [ { prop1: 3, prop2: '3FDE' }, { prop1: 4, prop2: '5ZFR' }, { 
prop1: 5, prop2: '7ABR' } ];

const _getLastThree = (str = '') => str.substr(str.length - 3);
const res = arr.sort(({ prop2: a }, { prop2: b }) => 
  _getLastThree(a).localeCompare(_getLastThree(b))
);

console.log(res);

Answer №2

To manipulate and sort arrays or strings in JavaScript, you have several methods at your disposal such as Array#sort, String#substring, String#slice, String#substr, and String#localCompare.

  • substring

const arr = [ {prop1:4, prop2:'5ZFR'}, {prop1:5, prop2:'7ABR'}, {prop1:3, prop2:'3FDE'} ];

const output = arr.sort(
   (a,b) => 
   a.prop2.substring(1).localeCompare( b.prop2.substring(1) )
);

console.log( output );

Another option is to utilize the slice or substr method with a negative value to extract and compare the last characters:

const arr = [ {prop1:4, prop2:'5ZFR'}, {prop1:5, prop2:'7ABR'}, {prop1:3, prop2:'3FDE'} ];

const output = arr.sort(
   (a,b) => 
   a.prop2.slice(-3).localeCompare( b.prop2.slice(-3) )
);

console.log( output );

Answer №3

To achieve this, simply utilize the .localeCompare() method along with the .slice() function:

const data=[
{val1:8, val2:'HJKR'},
{val1:6, val2:'7FDE'},
{val1:9, val2:'ABCZ'},
]


var ascendingArr, descendingArr;
console.log(ascendingArr=data.slice(0).sort((a,b)=>a.val2.slice(-3).localeCompare(b.val2.slice(-3))));

// For a descending order, use
console.log(descendingArr=data.slice(0).sort((a,b)=>-a.val2.slice(-3).localeCompare(b.val2.slice(-3)));

// Alternatively, reverse the array obtained 
console.log(descendingArr=ascendingArr.reverse());

It's important to recognize that the two usage instances of slice() are associated with different prototypes: .slice(0) is tied to an Array, creating a duplicate array copy, while .slice(-3) pertains to a String, removing the last three characters from it.

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

I am having trouble with setInterval not functioning as expected. I am trying to make a function repeat every 500ms using setInterval, but it seems to be ineffective

var direction; function movement(){ switch(direction){ case 1: positionX = positionX + 10; break; case 2: positionX = positionX - 10; break; case 3: positionY = positionY - 10; bre ...

Update the useMemo state value after the initial function block has been executed

Currently, I have a list of characters from Dragon Ball Z that users can filter based on gender, race, or both using useMemo. let dbzCharacters = useMemo<CharacterObj[]>(() => { if (filterGenderValue && filterRaceValue) { retur ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...

Output the value of each key from an array only if the corresponding key in a second array

There are two arrays at play: $choices = array ( [model] => 3D Modeling / BIM [edb] => Engineering & Design-Build [gse] => Green & Sustainable Energy [ipd] => Integrated Project Design [lc] => ...

Node JS Promise does not provide a value as a return

Struggling with getting a value back from the code snippet below, even though it console logs out without any issues. Any suggestions on how to assign a value to X? var dbSize = dbo.collection('Items').count() var x = 0 x = dbS ...

Modifying the CSS design of specific columns within a table created using JavaScript

A unique way to showcase JSON data in a table is by utilizing a for loop within a function. This method, however, does not assign an ID or Class to the table. To hide the final three columns of this table using CSS, the following code can be employed (whe ...

Managing an unexpected variable when making an AJAX request

Here is a code snippet that I am working with: var User = { get: function (options) { var self = this; $.ajax({ url: options.url, success: function (data, response) { self.nextPageUrl = data.pagination.next_page; opt ...

Creating DIV's with Equal Heights Using AngularJS ng-repeat

I'm currently facing an issue with aligning two side-by-side divs to the same height when the content is generated using an ng-repeat function. Using flexbox is causing responsiveness issues, and I'm unsure of the appropriate time to call a jQuer ...

python using selenium to bypass javascript popups

I have a project where I need to visit a specific website and interact with it using the Python selenium module. However, I am encountering a popup (a cookie acceptance form) when trying to access the site with a bot. I must accept this popup in order to p ...

The validation feature in 1000hz Bootstrap seems to be malfunctioning

I've been working on implementing validation using the 1000hz bootstrap validation plugin. Most things are going smoothly, but I'm encountering two issues: 1). The data-match attribute doesn't seem to be working even when I enter the same p ...

Utilizing an Immediate-Invoked Function Expression (IIFE) for jQuery in JavaScript

I'm looking at this code snippet that I believe is an Immediately Invoked Function Expression (IIFE). But, I'm confused about the role of (jQuery) and ($). I understand that it involves passing a reference to jQuery into the IIFE, but can someone ...

Managing multiple changes in input values within an object

Looking to update multiple input field values using the handleChange() method with a starter object that includes its own properties. The goal is to assign input field values to corresponding properties within the starter object. However, the current imple ...

Struggling to implement .indexOf() in conjunction with .filter()

Hello, I'm new to JavaScript and ES6. Currently, I am working on a react-native app that utilizes Firebase and Redux. One of my action creators acts as a search bar function to fetch data from Firebase. Here's the code I have so far: export cons ...

Automatically redirect to the linked page once the video concludes

Would it be feasible for a html5 video to trigger the opening of a new page upon completion? What would be the approach to achieve this using javascript? ...

Using AngularJS to pass objects dynamically through ng-include

Below is an example that is fully functional, except for one issue. When using node.title within the HTML code, everything works as expected. However, when trying to use {{node.title}} within the ng-include file, it does not function properly. Only the g ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Adjusting canvas context position after resizing

I've been experimenting with using a canvas as a texture in three.js. Since three.js requires textures to have dimensions that are powers of two, I initially set the canvas width and height to [512, 512]. However, I want the final canvas to have non-p ...

Code for Custom Controllers in Strapi Beta version 3.0

I have encountered some discrepancies in the beta version of Strapi's controllers compared to the previous version. The new version includes multipart/sanitization boilerplate, and I am having trouble integrating my order object and Stripe charge. Be ...

Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to ...