JavaScript如何将数字数组转换为数值对应出现索引的映射对象
实现方案
你可以利用Array.prototype.reduce回调的第三个参数(当前遍历元素的索引)完成需求,具体实现如下:
推荐实现(值统一为索引数组)
const arr = [12,14,12,10,11,10]; const result = arr.reduce((accumulator, currentValue, currentIndex) => { // 若当前值对应的键不存在,先初始化为空数组 if (!accumulator[currentValue]) { accumulator[currentValue] = []; } // 将当前索引加入对应数组 accumulator[currentValue].push(currentIndex); return accumulator; }, {}); // 初始累加值为空对象
运行后result的输出为:
{ '10': [ 3, 5 ], '11': [ 4 ], '12': [ 0, 2 ], '14': [ 1 ] }
该实现所有值的类型统一为数组,后续无需额外做类型判断,更便于后续逻辑处理。
匹配示例格式(单个索引直接存数字)
如果你确实需要和你给出的示例格式一致,单个出现的数值直接存索引数字,可以用以下实现:
const arr = [12,14,12,10,11,10]; const result = arr.reduce((accumulator, currentValue, currentIndex) => { if (accumulator[currentValue] === undefined) { // 第一次出现直接存储索引数字 accumulator[currentValue] = currentIndex; } else if (Array.isArray(accumulator[currentValue])) { // 已经是数组的情况直接追加索引 accumulator[currentValue].push(currentIndex); } else { // 第二次出现,把原有数字转为数组再追加新索引 accumulator[currentValue] = [accumulator[currentValue], currentIndex]; } return accumulator; }, {});
运行后result的输出为:
{ '10': [ 3, 5 ], '11': 4, '12': [ 0, 2 ], '14': 1 }
该方案值的类型不统一,后续处理需要额外判断类型,不推荐使用。
内容的提问来源于stack exchange,提问作者sk65plus
相关产品推荐
相关产品推荐

