Home > Blockchain >  Splitting an array with N arrays of a value pair, into set N sets
Splitting an array with N arrays of a value pair, into set N sets

Time:04-25

Any help or suggestion on how to achieve please?

I have a group of 8 teams

    teamArray  =['Team_1', 'Team_2', 'Team_3', 'Team_4', 'Team_5', 'Team_6', 'Team_7', 'Team_8']

and use the following function to pair each team which give 28 pairs

    let pairs = teamArray.flatMap(
        (v, i) => teamArray.slice(i 1).map( w => [v,w] )
    );

Now I want to take the 28 pairs and split into 7 arrays of with 4 pairs, while each array cannot have an pair with one value more than once?

an example of the desired output:

result  = [
[['Team_1', 'Team_2'], ['Team_3', 'Team_4'], ['Team_5', 'Team_6'], ['Team_7', 'Team_8']],
[['Team_1', 'Team_3'], ['Team_2', 'Team_4'], ['Team_5', 'Team_7'], ['Team_6', 'Team_8']],
...]

CodePudding user response:

Seems like a task for the reduce method of an array:

result = pairs.reduce((accumulator, currentPair) => {
    let match = accumulator.find(array => !array.some(pair => currentPair.some(ci => pair.some(i => ci === i))));
    if (match !== undefined) {
        match.push(currentPair);
        return accumulator;
    }
    else {
        accumulator.push([currentPair]);
        return accumulator;
    }
}, []);
  • Related