Reputation: 1294
How can I sort the following array, in a custom order, based on the prop2
's last 3 letters that have to be in this order 'ABR', 'FDE', 'ZFR' and also in descending order 'ZFR', 'FDE', 'ARB' for another array.
Sample input:
const arr = [
{ prop1: 3, prop2: '3FDE' },
{ prop1: 4, prop2: '5ZFR' },
{ prop1: 5, prop2: '7ABR' }
]
Expected 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' }
]
Upvotes: 1
Views: 100
Reputation: 28206
Just use .localeCompare()
in combination with .slice()
:
const arr=[
{prop1:5, prop2:'7ABR'},
{prop1:3, prop2:'3FDE'},
{prop1:4, prop2:'5ZFR'},
]
var ascArr,dscArr;
console.log(ascArr=arr.slice(0).sort((a,b)=>a.prop2.slice(-3).localeCompare(b.prop2.slice(-3))));
// for descending order just do
console.log(dscArr=arr.slice(0).sort((a,b)=>-a.prop2.slice(-3).localeCompare(b.prop2.slice(-3))));
// or reverse the resulting array with
console.log(dscArr=ascArr.reverse());
Please note that the two slice()
methods belong to different prototypes: .slice(0)
is an Array
method that essentially creates a flat copy of the original array while .slice(-3)
is a String
method that "shaves off" the last three characters of the string.
Upvotes: 1
Reputation: 24638
You can use the Array#sort
, String#substring
or String#slice
or String#substr
and the String#localCompare
methods as follows:
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 );
With slice
or substr
you can use a negative n to indicate the last n 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 );
Upvotes: 1
Reputation: 28424
Array#sort
, iterate over the array to sort itString#substr
to get the last 3 characters and String#localeCompare
to compare the two stringsconst 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);
Upvotes: 1