数组去重+排序

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>数组去重排序</title>
</head>

<body>
  <script>
    // 数组去重
    // 方法一(原理性):
    var arr = [2, 5, 12, 21, 54, 22, 61, 6, 1, 72, 4, 1, 3, 5, 3, 51, 4, 2, 22]
    var result = []
    for (var i = 0; i < arr.length; i++) {
      var flag = true
      for (var j = 0; j < result.length; j++) {
        if (arr[i] === result[j]) {
          flag = false
          break
        }
      }
      if (flag === true) {
        result[result.length] = arr[i]
      }
    }
    // 方法二:
    // var result = new Set(arr)

    // 数组排序
    var res = result.sort(function(a, b) {
        // return a - b
        return b - a
      })
      // 倒叙  reverse() 相当于return b-a
      // console.log(result.reverse())
    console.log(result)
  </script>
</body>

 

posted @ 2019-12-25 11:30  枚齐元子  阅读(206)  评论(0编辑  收藏  举报