如何在JavaScript中自动提取列表中分组元素的选中项
问题描述
现有三个问卷对象数组 PHQ、GAD、RSES,它们的元素被交叉组合成数组 qnaList;同时存在一个 select 数组,每个元素对应 qnaList 中对应位置元素的选中答案索引。需要实现逻辑,将 select 中的值按原问卷分组,提取为 selectedPHQ、selectedGAD、selectedRSES 三个数组。示例最终结果:
selectedPHQ = [3,0,3]selectedGAD = [2,1,2]selectedRSES = [1,2,1]
实现思路与代码
核心是根据 qnaList 的交叉组合规则,从 select 中匹配对应分组的索引值,以下是两种常见组合规则的实现:
情况1:轮询式交叉组合(PHQ第1个→GAD第1个→RSES第1个→PHQ第2个→...)
// 示例输入数据 const PHQ = [{id: 'phq1'}, {id: 'phq2'}, {id: 'phq3'}]; const GAD = [{id: 'gad1'}, {id: 'gad2'}, {id: 'gad3'}]; const RSES = [{id: 'rses1'}, {id: 'rses2'}, {id: 'rses3'}]; const select = [3, 2, 1, 0, 1, 2, 3, 2, 1]; // 提取逻辑 const selectedPHQ = []; const selectedGAD = []; const selectedRSES = []; // 假设三个问卷长度一致,若长度不同需额外处理边界 const groupCount = 3; const itemCount = PHQ.length; for (let i = 0; i < itemCount; i++) { selectedPHQ.push(select[i * groupCount]); selectedGAD.push(select[i * groupCount + 1]); selectedRSES.push(select[i * groupCount + 2]); } console.log(selectedPHQ); // [3, 0, 3] console.log(selectedGAD); // [2, 1, 2] console.log(selectedRSES); // [1, 2, 1]
情况2:按问卷整体拼接(PHQ全部元素→GAD全部元素→RSES全部元素)
// 示例输入数据 const PHQ = [{id: 'phq1'}, {id: 'phq2'}, {id: 'phq3'}]; const GAD = [{id: 'gad1'}, {id: 'gad2'}, {id: 'gad3'}]; const RSES = [{id: 'rses1'}, {id: 'rses2'}, {id: 'rses3'}]; const select = [3, 0, 3, 2, 1, 2, 1, 2, 1]; // 提取逻辑 const phqLen = PHQ.length; const gadLen = GAD.length; const selectedPHQ = select.slice(0, phqLen); const selectedGAD = select.slice(phqLen, phqLen + gadLen); const selectedRSES = select.slice(phqLen + gadLen); console.log(selectedPHQ); // [3, 0, 3] console.log(selectedGAD); // [2, 1, 2] console.log(selectedRSES); // [1, 2, 1]
关键说明
- 必须明确
qnaList的交叉组合规则,这是提取逻辑的核心依据,不同组合规则对应不同的索引匹配方式 - 若三个问卷数组长度不一致,轮询式组合需额外判断索引是否越界,避免报错
内容的提问来源于stack exchange,提问作者박혜찬
相关产品推荐
相关产品推荐

