Евгений Усов - 1 month ago 8
Javascript Question

# Algorithm for generate matrix pairs lists from elements

I don't know how to formulate right. But I need to make next thing.

We have next data stucture:

``````a = [
{
name: "size",
'values': ['S', 'M', 'L']
},
{
name: 'color',
'values': ['B', 'G', 'Y'],
},
{
name: 'material',
'values': ['X', 'Y']
}
]
``````

And from this need generate next array:

``````['SBX', 'SBY', 'SGX', 'SGY', 'SYX', 'SYY', 'MBX, 'MBY', ..., 'LYY']
``````

Exists some algorithm for my task? Or simple example. Thank you!

First: combine your values in one array. you can do that using Array#reduce

``````var a = [
{
name: "size",
'values': ['S', 'M', 'L']
},
{
name: 'color',
'values': ['B', 'G', 'Y'],
},
{
name: 'material',
'values': ['X', 'Y']
}
]
// Merge values together in one array
var values = a.reduce((acc, item) => {
acc.push(item.values);
return acc;
}, []);
``````

Then use a helper function to generate the possible values.

``````// Helper function
function allPossibleCases(arr) {
if (arr.length == 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1));  // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}
``````

Then pass your big array to this function

``````var outPut = allPossibleCases(values);
``````

All code:

``````var a = [{
name: "size",
'values': ['S', 'M', 'L']
},
{
name: 'color',
'values': ['B', 'G', 'Y'],
},
{
name: 'material',
'values': ['X', 'Y']
}
]
// Merge values together in one array
var values = a.reduce((acc, item) => {
acc.push(item.values);
return acc;
}, []);

// Helper function
function allPossibleCases(arr) {
if (arr.length == 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}

var outPut = allPossibleCases(values);

console.log(outPut);
/*
[
"SBX",
"MBX",
"LBX",
"SGX",
"MGX",
"LGX",
"SYX",
"MYX",
"LYX",
"SBY",
"MBY",
"LBY",
"SGY",
"MGY",
"LGY",
"SYY",
"MYY",
"LYY"
]
*/``````