kevin ternet - 1 year ago 87
Javascript Question

# Can't figure out a mapreduce algorithm

I have this input array already sorted on the key:

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

I want to obtain this reduced Array :

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

I proceed like that :

``````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);
``````

But I can't understand why I obtain this result:

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

Help would be apreciated.

The issue is that you're splicing your array while iterating over it without resetting your current index. One way to get the desired result while using splice is to do something like this:

``````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);
}
});
``````

Basically we're changing the `if` statement to a `while` loop and adding an extra check.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download