js数组汉字排序?

image.png
图中数组如何排序成

["2019一季报","2019二季报","2019半年报","2019三季报","2019四季报","2019年报"]
阅读 2.4k
5 个回答
const names = ['一季报','二季报','半年报','三季报','四季报','年报']
const arr = ["2019一季报","2019二季报","2019半年报","2019三季报","2019四季报","2019年报"]
const f = i => i.slice(0, 4) + names.indexOf(i.slice(4))
arr.sort((a, b) => f(a) > f(b))

这种就只能自己写一个 sort 方法了,因为中文的排序你没办法直接用 sort

因为 ['一季报','二季报','半年报','三季报','四季报','年报'].sort()
自动排序之后输出其实是:['一季报', '三季报', '二季报', '半年报', '四季报', '年报']

所以只能自己写一个排序的表然后去做匹配,比如说:

function sortFn(str,str2){
  var sortList = ['一季报','二季报','半年报','三季报','四季报','年报']
  var year1 = Number(str.match(/\d+\d?/g).pop())
  var year2 = Number(str2.match(/\d+\d?/g).pop())
  var word1 = str.match(/[\u4000-\uFFFF]+[\u4000-\uFFFF]?/g).pop()
  var word2 = str2.match(/[\u4000-\uFFFF]+[\u4000-\uFFFF]?/g).pop()
  if(year1 === year2) {
    return sortList.indexOf(word1) - sortList.indexOf(word2)
  } else {
    return year1 - year2
  }
}

['2019三季报', '2019半年报','2019年报', '2019四季报', '2020一季报',  '2019二季报', '2019一季报'].sort(sortFn)
// ['2019一季报', '2019二季报', '2019半年报', '2019三季报', '2019四季报', '2019年报', '2020一季报']

相关阅读

Array.prototype.sort() - JavaScript | MDN
String.prototype.match() - JavaScript | MDN
Array.prototype.indexOf() - JavaScript | MDN

let arr = ["2019二季报","2019一季报","2019半年报","2019四季报","2019三季报","2019年报"]
let arr1 = ["2020一季报","2020年报","2020四季报","2020三季报","2020二季报"]
const getIndex = v => {
  // 以standardArr为排序的标准
  let standardArr = ['一季报','二季报','半年报','三季报','四季报','年报']
  return standardArr.findIndex(it => v.includes(it))
}
 // 使用[...item])扩展运算符所以不会改变原数组,返回的是一个排好序的数组
const sortData = ([...item]) => item.sort((v1, v2) => getIndex(v1) - getIndex(v2))
console.log(sortData(arr))
console.log(sortData(arr1))

换个思路试试呢?你最终要做的是根据arr里面特殊字符排序,那就手动压入试试,代码如下:

const arr1 = ["2019半年报","2019二季报","2019四季报","2019三季报","2019年报","2019一季报"];

const arr2 = [];

arr1.forEach((item) => {
  if (item.includes('一')) {
    arr2[0] = item;
  } else if (item.includes('二')) {
    arr2[1] = item;
  } else if (item.includes('半年')) {
    arr2[2] = item;
  } else if (item.includes('三')) {
    arr2[3] = item;
  } else if (item.includes('四')) {
    arr2[4] = item;
  } else if (item.includes('年报')) {
    arr2[5] = item;
  }
});

console.log(arr2);  // ["2019一季报","2019二季报","2019半年报","2019三季报","2019四季报","2019年报"]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏