javascript - 根据当前元素和先前元素之间的差异对排序数组进行分组
问题描述
我有一个按升序排序的数组:
const arr=[ 1, 2, 3, 5, 6, 7, 10, 12, 17, 18]
我必须对它进行分组,以便:
- 组内的元素相差
1
小于等于 - 每个组元素应该有多个元素被认为是有效的
基于上述条件,预期输出为:
const resultArr=[
[1, 2, 3],
[5, 6, 7],
[17, 18]//each has more than one element
]
好的,此时我的大脑几乎停止了..
我尝试的是:
let prev = arr[0];
const resultArr = [prev];
for (let i = 1; i < arr.length; i++) {
const curr = arr[i];
if (curr - prev <= 1) {
resultArr.push(curr);
} else {
resultArr.shift();
}
prev = curr;
}
非常感谢帮助!
reduce
编辑:如果有没有功能的解决方案会很棒
解决方案
您可以检查前任并将值添加到结果集的最后一个数组或检查下一个值是否有效,然后将新组添加到结果集中。
const
array = [1, 2, 3, 5, 6, 7, 10, 12, 17, 18],
result = array.reduce((result, value, index, array) => {
if (array[index - 1] + 1 === value) result[result.length - 1].push(value);
else if (value + 1 === array[index + 1]) result.push([value]);
return result;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
一个带有经典循环的。
const
array = [1, 2, 3, 5, 6, 7, 10, 12, 17, 18],
result = [];
for (let index = 0; index < array.length; index++) {
let value = array[index];
if (array[index - 1] + 1 === value) {
result[result.length - 1].push(value);
} else if (value + 1 === array[index + 1]) {
result.push([value]);
}
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- mysql - 哪种方法更快,效率更高?
- c++ - __FLT_MAX__ 和 __DBL_MAX__ 为 0?
- sql-server - T-SQL 如何对文本数据求和?
- mysql - 将一列从一个表移动到另一个mysql
- python - 将 tensorflow 冻结图转换为 pbtxt 文件失败
- coding-style - 如何让 clang-format 不将简单的枚举格式化为一行?
- ruby-on-rails - how to apply :session_limitable at a specific user ? (devise-security )
- python - 使用python 3将csv数据导入mysql数据库时出错
- javascript - 我可以在对话框中的画布内显示输赢游戏后的结果,而不是使用“警报”吗?
- excel - 将 Outlook 电子邮件数量、期限和受益人解析为 Excel