有没有一种简单的方法可以按范围对js数组值进行分组? [英] Is there a simple way to group js array values by range?

查看:46
本文介绍了有没有一种简单的方法可以按范围对js数组值进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个如下所示的js数组,是否有一种简单的方法可以按范围对数组值进行重新分组,逻辑基于范围步长,范围步长为1,所以如果数组值连续增加减1,则应写为"1-3",否则应该折成另一组,非常感谢!

if I have a js array like below, is there a simple way to re-group the array values by range, the logic is based on the range step, the range step is 1, so if the array values are continuous increased by 1, then it should be write like "1-3", otherwise it should be break to another group, thanks a lot!

var list = ["1", "2", "3", "5", "6", "9", "12", "13", "14", "15", "16"]

function(list) {

    // * some function here //

    return ["1-3", "5-6", "9", "12-16"]
}

推荐答案

您可以使用

You could use Array#reduce for it.

var array = ["1", "2", "3", "5", "6", "9", "12", "13", "14", "15", "16"],
    result = array.reduce(function (r, a, i, aa) {
        r.push(!i || aa[i - 1] - a + 1 ? a : r.pop().split('-')[0] + '-' + a);
        return r;
    }, []);

console.log(result);

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

这篇关于有没有一种简单的方法可以按范围对js数组值进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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