最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery sort array value in sequence - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Oct 26, 2017 at 18:38 worpet 3,8932 gold badges33 silver badges55 bronze badges asked Oct 10, 2017 at 8:34 Soft One GlobalSoft One Global 1758 bronze badges 1
  • Have you done any research into Array sort? – evolutionxbox Commented Oct 10, 2017 at 8:36
Add a comment  | 

1 Answer 1

Reset to default 29

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 sorting happens with the group and index.

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((value, index) => ({ index, group: groups[value] = (groups[value] || 0) + 1 }))
        .sort((a, b) => a.group - b.group || a.index - b.index)
        .map(({ index }) => array[index]);

console.log(...result);

发布评论

评论列表(0)

  1. 暂无评论