jQuery按顺序排序数组值 [英] jQuery sort array value in sequence

查看:125
本文介绍了jQuery按顺序排序数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组 [1,1,1,1,2,2,2,3,3] 我希望将其转换为 [1,2,3,1,2,3,1,1] 使用jQuery。我没有代码,也不知道我该怎么办。

I have an array like this [1,1,1,1,2,2,2,3,3] and I want to convert this into [1,2,3,1,2,3,1,1] using jQuery. I have no code and no idea how can I do this.

推荐答案

你可以使用使用带有哈希表的临时对象的地图排序组数组。从中获取已使用数组的长度作为排序组。

You could use sorting with map by using a temporary object with a hashtable for the same group array. Take from it the length of the used array as group for sorting.

对组和索引进行排序。

结果与已排序的临时数组的索引映射。

The result is mapped with index of the sorted temporary array.

var array = [1, 1, 1, 1, 2, 2, 2, 3, 3],
    groups = Object.create(null),
    result = array
        .map(function (a, i) {
            return { index: i, group: (groups[a] = groups[a] || []).push(a) };
        })
        .sort(function (a, b) {
            return a.group - b.group || a.index - b.index;
        })
        .map(function (o) {
            return array[o.index];
        });


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于jQuery按顺序排序数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆