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'
Sample input:
const arr = [
{ prop1: 3, prop2: '3FDE' },
{ prop1: 4, prop2: '5ZFR' },
{ prop1: 5, prop2: '7ABR' }
]
Expected output:
const arr = [
{ prop1: 5, prop2: '7ABR' },
{ prop1: 3, prop2: '3FDE' },
{ prop1: 4, prop2: '5ZFR' }
]
CodePudding user response:
- Using
Array#sort
, iterate over the array to sort it - In every iteration, use
String#substr
to get the last 3 characters andString#localeCompare
to compare the two strings
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);
CodePudding user response:
Just use .localeCompare()
in combination with .slice()
:
const arr=[
{prop1:5, prop2:'7ABR'},
{prop1:3, prop2:'3FDE'},
{prop1:4, prop2:'5ZFR'},
]
console.log(arr.sort((a,b)=>a.prop2.slice(-3).localeCompare(b.prop2.slice(-3))))
CodePudding user response:
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 );