1. 程式人生 > 實用技巧 >js 陣列根據特定規則排序

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>