js任意数组自定义排序

发布时间:2023年12月29日

2023.12.29今天我学习了如何对自定义的数组进行排序,如:

假如我们有一个这样的数组,我们需要按照字母的顺序进行排序,

这是考虑含有字母和数字的情况:

代码如下:

<template>

</template>
<script>
export default {
  data() {
    return {}
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      let demo = [
        {name: 'w房间05'},
        {name: 'w房间02'},
        {name: 'w房间03'},
        {name: 'w房间01'},
        {name: '其他房间'},
        {name: 'a房间03'},
        {name: 'a房间01'},
        {name: 'a房间02'},
      ]
       demo.sort((a, b) => {
        const sort_a = this.roomSortKey(a)
        const sort_b = this.roomSortKey(b)
        return sort_a.localeCompare(sort_b)
      })
    },
    // 定义排序函数
    roomSortKey(room) {
      const roomName = room.name;
      // 提取房间名称中的数字和字母部分
      const match = roomName.match(/\d+|[a-zA-Z]+/);
      if (match) {
        const roomCode = match[0];
        if (roomCode.startsWith("a")) {//判断是否为a开头
          return "a" + roomName;
        } else if (roomCode.startsWith("w")) {//判断是否为b开头
          return "b" + roomName;
        }
      }
      return "z";//否则排到最后面
    },
  }
}
</script>

如果不含数字或字母,我们就需要直接去判断:

<template>

</template>
<script>
export default {
  data() {
    return {}
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      let demo = [
        {name: 'w房间05'},
        {name: 'w房间02'},
        {name: 'w房间03'},
        {name: '其他房间'},
        {name: '别墅'},
        {name: '民房'},
        {name: 'w房间01'},
        {name: 'a房间03'},
        {name: 'a房间01'},
        {name: 'a房间02'},
      ]
      demo.sort((a, b) => {
        const sort_a = this.roomSortKey(a)
        const sort_b = this.roomSortKey(b)
        return sort_a.localeCompare(sort_b)
      })
    },
    // 定义排序函数
    roomSortKey(room) {
      const roomName = room.name;
      // 提取房间名称中的数字和字母部分
      const match = roomName.match(/\d+|[a-zA-Z]+/);
      if (match) {
        const roomCode = match[0];
        if (roomCode.startsWith("a")) {
          return "a" + roomName;
        } else if (roomCode.startsWith("w")) {
          return "b" + roomName;
        }
      } else {
        if (roomName == '别墅') {
          return 'd'
        } else if (roomName == '民房') {
          return 'c'
        }
      }
      return "z";
    },
  }
}
</script>

文章来源:https://blog.csdn.net/qq_53986004/article/details/135283004
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。