使用Ramda根据序列逻辑条件拆分带aspectRatio的图片数组
解决图片数组按宽高比条件分组的问题
我懂你的痛点——splitWhen这类方法确实只能基于当前元素做拆分判断,没法向前回溯统计连续元素的情况,要实现你需要的这种动态分组规则,我们可以手动遍历数组并维护状态来处理。
需求回顾
- 默认每2个元素分为一组
- 当**连续出现3个
aspectRatio < 1**的元素时,将这3个作为单独一组 - 分组要兼顾两种规则,比如示例中剩下的单个小比例元素会和后面的大比例元素组成默认的2元素组
实现代码
这里用JavaScript写一个通用的分组函数,完全匹配你的需求:
function groupPhotos(photos) { const result = []; let currentGroup = []; let consecutiveSmallRatio = 0; // 记录连续aspectRatio<1的元素数量 for (const photo of photos) { const isSmallRatio = photo.fluid.aspectRatio < 1; // 更新连续小比例元素计数 consecutiveSmallRatio = isSmallRatio ? consecutiveSmallRatio + 1 : 0; currentGroup.push(photo); // 判断是否需要拆分当前分组 if (consecutiveSmallRatio === 3) { // 连续3个小比例,直接拆分这一组 result.push([...currentGroup]); currentGroup = []; consecutiveSmallRatio = 0; } else if (currentGroup.length === 2) { // 达到默认分组长度,拆分 result.push([...currentGroup]); currentGroup = []; // 重置连续计数:如果最后一个元素是小比例,计数设为1(因为下一个元素如果也是的话,要延续计数) consecutiveSmallRatio = isSmallRatio ? 1 : 0; } } // 处理最后剩下的不足2个的元素 if (currentGroup.length > 0) { result.push(currentGroup); } return result; } // 测试你的示例数组 const photos = [ { fluid: { aspectRatio: 1.5 } }, { fluid: { aspectRatio: 1.5 } }, { fluid: { aspectRatio: 0.67 } }, { fluid: { aspectRatio: 0.67 } }, { fluid: { aspectRatio: 0.67 } }, { fluid: { aspectRatio: 0.67 } }, { fluid: { aspectRatio: 1.5 } }, { fluid: { aspectRatio: 1.5 } }, { fluid: { aspectRatio: 0.67 } } ]; const result = groupPhotos(photos); console.log(result);
代码说明
- 状态维护:用
consecutiveSmallRatio跟踪连续的小比例元素数量,每次遇到大比例元素就重置为0 - 分组判断逻辑:
- 优先检查是否达到连续3个小比例:如果是,直接拆分当前3元素组
- 否则检查是否达到默认的2元素长度:拆分后根据最后一个元素的类型重置连续计数(比如最后一个是小比例,下一个元素如果也是的话,要从1开始计数)
- 边界处理:遍历结束后把剩余的元素(不足2个的)加入结果
运行这段代码后,得到的结果和你期望的完全一致:
[ [ { fluid: { aspectRatio: 1.5 } }, { fluid: { aspectRatio: 1.5 } } ], [ { fluid: { aspectRatio: 0.67 } }, { fluid: { aspectRatio: 0.67 } }, { fluid: { aspectRatio: 0.67 } } ], [ { fluid: { aspectRatio: 0.67 } }, { fluid: { aspectRatio: 1.5 } } ], [ { fluid: { aspectRatio: 1.5 } }, { fluid: { aspectRatio: 0.67 } } ] ]
这种手动遍历的方式比splitWhen更灵活,能处理需要回溯或统计连续元素的分组场景。
内容的提问来源于stack exchange,提问作者gosseti
相关产品推荐
相关产品推荐

