2

I'm trying to get a permutations function to work but it's confusing me.

example dataset:

{
    a: [1,2],
    b: [1,2,3],
    c: [1,2]
}

desired output:

[
    [ 'a-1', 'b-1', 'c-1' ],
    [ 'a-1', 'b-1', 'c-2' ],
    [ 'a-1', 'b-2', 'c-1' ],
    [ 'a-1', 'b-2', 'c-2' ],
    [ 'a-1', 'b-3', 'c-1' ],
    [ 'a-1', 'b-3', 'c-2' ],
    [ 'a-2', 'b-1', 'c-1' ],
    [ 'a-2', 'b-1', 'c-2' ],
    [ 'a-2', 'b-2', 'c-1' ],
    [ 'a-2', 'b-2', 'c-2' ],
    [ 'a-2', 'b-3', 'c-1' ],
    [ 'a-2', 'b-3', 'c-2' ],
]

So far I've iterated over the Object, then iterated over the Array for each key and then need to do that all again..

To start I broke the values out like so:

[
    [ 'a-1', 'a-2' ],
    [ 'b-1', 'b-2', 'b-3' ],
    [ 'c-1', 'c-2' ]
]

then iterated over them:

var list_joined = []
var list = []
array.forEach((key, index) => {
    key.forEach((value) => {
        var tmp = [value]
        array.forEach((_value, _index) => {
            if(_index != index) {
                tmp.push(_value[0])
            }
        })
        tmp = tmp.sort()
        if(list_joined.indexOf(tmp.join('_')) < 0) {
            list_joined.push(tmp.join('_'))
            list.push(tmp)
        }
    })
})

result

[
    [ 'a-1', 'b-1', 'c-1' ],
    [ 'a-1', 'b-1', 'c-2' ],
    [ 'a-1', 'b-2', 'c-1' ],
    [ 'a-1', 'b-3', 'c-1' ],
    [ 'a-2', 'b-1', 'c-1' ]
]

I can't quite put my finger on where to fix the iterative process.

1 Answer 1

2

You could use an iterative and recursive approach for it.

function combine(object) {

    function c(part, index) {
        object[keys[index]].forEach(function (a) {
            var p = part.concat(keys[index] + '-' + a);
            if (p.length === keys.length) {
                r.push(p);
                return;
            }
            c(p, index + 1);
        });
    }

    var keys = Object.keys(object),
        r = [];

    c([], 0);
    return r;
}

var data = { a: [1, 2], b: [1, 2, 3], c: [1, 2] },
    result = combine(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! question: did you just write that free hand or have something similar stashed away?
it's part of a canon (of me).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.