javascript - 将数字的javascript数组拆分为范围

标签 javascript arrays sorting split

我有一个数组,例如:

[16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12]

我想根据范围 1-4、5-8、9-12、13-16、17-20、21-24 分成 6 个不同的数组。

使用 javascript 执行此操作的最简单方法是什么?

最佳答案

您可以使用间隔将数字分配给特定的插槽。

var array = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12],
    interval = 4,
    result = array.reduce(function (r, a) {
        var slot = Math.floor((a - 1) / interval);
        (r[slot] = r[slot] || []).push(a);
        return r;
    }, []);

console.log(result);

关于javascript - 将数字的javascript数组拆分为范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42099244/

相关文章:

javascript - CckEditor 与 jquery 表单冲突

将 C 数组中的字节转换为 long

c++ - 从数组中查找中间元素

Python按时间字符串对二维列表进行排序

javascript - jQuery inArray() 总是返回 -1

javascript - 如何使倒计时可与对象重复使用?

php - 从 JavaScript 调用 php 函数

javascript - 如何使用 css3 翻转并更改元素?

php - 如何在循环中使用数组的一部分?

Bash - 数字排序在 1 秒之前排序 10 秒