关于数组通过汉字(中文)自定义排序js

112 阅读1分钟

原数组👇

image.png

需变成👇

image.png

实现🙂

image.png

` <script>
        // 原数组
        let data = [
            { name: '香蕉', id: 1 },
            { name: '西瓜', id: 2 },
            { name: '荔枝', id: 3 },
            { name: '菠萝', id: 4 }
        ]

        const resultSort = ["荔枝", "西瓜", "菠萝", "香蕉"];  // 自定义排序

        data.sort((a, b) => resultSort.indexOf(a.name) - resultSort.indexOf(b.name));
    </script>`