js 数组根据特定规则排序

直接上代码:

<!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>
        (function myArrayMin() {
            //按照order数组中数据位置给arr数组 排序
            var order = ["wipe", "fly", "iris", "flip", "cube"];
            var arr = [
                { 'name': 'A', 'type': 'fly' },
                { 'name': 'B', 'type': 'blur' },
                { 'name': 'C', 'type': 'wipe' },
                { 'name': 'D', 'type': 'cube' },
                { 'name': 'E', 'type': 'iris' },
                { 'name': 'F', 'type': 'fade' }
            ];
            arr.sort((a, b) => {
                return order.indexOf(a.type) - order.indexOf(b.type);
            });
            console.log(arr)
            /**
             * 输出: 
             * (6) [{…}, {…}, {…}, {…}, {…}, {…}]
                   0: {name: "B", type: "blur"}
                   1: {name: "F", type: "fade"}
                   2: {name: "C", type: "wipe"}
                   3: {name: "A", type: "fly"}
                   4: {name: "E", type: "iris"}
                   5: {name: "D", type: "cube"}
                   length: 6
               __proto__: Array(0)
             * 
            */
        })()
    </script>
</body>

</html>
原文地址:https://www.cnblogs.com/a1-top/p/14072891.html