gpt4 book ai didi

javascript - 无法弄清楚mapreduce算法

转载 作者:行者123 更新时间:2023-11-28 15:05:57 25 4
gpt4 key购买 nike

我已经在键上对这个输入数组进行了排序:

var sortedArray = [ [ 'de', [ 1 ] ],
[ 'elle', [ 1 ] ],
[ 'elle', [ 1 ] ],
[ 'la', [ 1 ] ],
[ 'la', [ 1 ] ],
[ 'la', [ 1 ] ],
[ 'le', [ 1 ] ],
[ 'maison', [ 1 ] ],
[ 'voiture', [ 1 ] ],
[ 'voiture', [ 1 ] ]
];

我想获得这个简化的数组:

[ [ 'de', [ 1 ] ],
[ 'elle', [ 1, 1 ] ],
[ 'la', [ 1, 1, 1 ] ],
[ 'le', [ 1 ] ],
[ 'maison', [ 1 ] ],
[ 'voiture', [ 1, 1 ] ]
];

我就这样进行:

sortedArray.forEach((elem, index, arr) => {
if (elem[0] === arr[index + 1][0]){
arr[index][1].push(1);
arr.splice(index + 1, 1);
}
});

console.log(sortedArray);

但我不明白为什么会得到这个结果:

 [ [ 'de', [ 1 ] ],
[ 'elle', [ 1, 1 ] ],
[ 'la', [ 1, 1 ] ],
[ 'la', [ 1 ] ],
[ 'le', [ 1 ] ],
[ 'maison', [ 1 ] ],
[ 'voiture', [ 1, 1 ] ]
]

我们将不胜感激。

最佳答案

问题是您在迭代数组时拼接数组而不重置当前索引。使用 splice 时获得所需结果的一种方法是执行以下操作:

sortedArray.forEach((elem, index, arr) => {
while (arr[index + 1] && elem[0] === arr[index + 1][0]){
arr[index][1].push(1);
arr.splice(index + 1, 1);
}
});

基本上,我们将 if 语句更改为 while 循环并添加额外的检查。

关于javascript - 无法弄清楚mapreduce算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38946877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com