[英]How to sort an array of objects based on the substring of property values
我如何根据prop2
的最后 3 个字母按自定义顺序对以下数组进行排序,这些字母必须按此顺序 'ABR'、'FDE'、'ZFR' 以及降序排列 'ZFR'、' FDE', 'ARB' 用于另一个数组。
示例输入:
const arr = [
{ prop1: 3, prop2: '3FDE' },
{ prop1: 4, prop2: '5ZFR' },
{ prop1: 5, prop2: '7ABR' }
]
预计 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' }
]
Array#sort
遍历数组以对其进行排序String#substr
获取最后 3 个字符,使用String#localeCompare
比较两个字符串 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);
只需将.localeCompare()
与.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());
请注意,这两个slice()
方法属于不同的原型: .slice(0)
是一个Array
方法,它本质上是创建原始数组的平面副本,而.slice(-3)
是一个String
方法,它“剃掉”字符串的最后三个字符。
您可以使用Array#sort
、 String#substring
或String#slice
或String#substr
和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 );
对于slice
或substr
,您可以使用负数 n 来表示最后 n 个字符:
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.