में ऑब्जेक्ट्स के कार्टेसियन उत्पाद को विशेषता गुणों को बरकरार रखने के दौरान, एन गुणों की सूची के आधार पर मुझे भिन्न प्रकारों का एक सेट सेट करना होगा।जावास्क्रिप्ट
var input = [
{ 'colour' : ['red', 'green'] },
{ 'material' : ['cotton', 'wool', 'silk'] },
{ 'shape' : ['round', 'square', 'rectangle'] }
];
var expected = [
{ 'colour': 'red', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'red', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'red', 'material': 'cotton', 'shape': 'rectangle' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'square' },
{ 'colour': 'red', 'material': 'wool', 'shape': 'rectangle' },
{ 'colour': 'red', 'material': 'silk', 'shape': 'round' },
{ 'colour': 'red', 'material': 'silk', 'shape': 'square' },
{ 'colour': 'red', 'material': 'silk', 'shape': 'rectangle' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'round' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'square' },
{ 'colour': 'green', 'material': 'cotton', 'shape': 'rectangle' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'round' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'square' },
{ 'colour': 'green', 'material': 'wool', 'shape': 'rectangle' },
{ 'colour': 'green', 'material': 'silk', 'shape': 'round' },
{ 'colour': 'green', 'material': 'silk', 'shape': 'square' },
{ 'colour': 'green', 'material': 'silk', 'shape': 'rectangle' }
];
सरणियों के कार्तीय उत्पादों के लिए चारों ओर एल्गोरिदम के बहुत सारे हैं, लेकिन मैं वस्तुओं है कि कुंजी को बरकरार रखता है के लिए एक खोजने के लिए प्रतीत नहीं कर सकते हैं।
प्रदर्शन एक बड़ी चिंता नहीं है क्योंकि प्रत्येक विशेषता के लिए कभी भी दर्जन से अधिक मूल्य नहीं होंगे। आदेश को expected
से बिल्कुल मेल नहीं करना पड़ेगा।
मैं एक प्रारंभिक सूचियों के मानक एल्गोरिदम के आधार पर प्रयास किया है, लेकिन मैं संघर्ष कर रहा हूँ:
function cartesianProduct(input, current) {
if (!input || input.length < 1) {
return [];
}
var head = input[0];
var tail = input.slice(1);
var output = [];
for (var key in head) {
for (var i = 0; i < head[key].length; i++) {
if (typeof current == 'undefined') {
var current = {};
}
current[key] = head[key][i];
var productOfTail = cartesianProduct(tail, current);
output.push(current);
console.log(current);
}
}
return output;
}
console.log(cartesianProduct(input));
[ऐसा ही एक सवाल यहाँ कहा गया है] (http://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in: उदाहरण के लिए इस कोड के साथ परिणाम प्राप्त कर सकते हैं -जास्क्रिप्ट) – Keithamus
आपके कोड में एक बड़ी समस्या है: आप मुझे एक var के रूप में घोषित नहीं करते हैं, इसलिए इसे वैश्विक var माना जाता है, इसलिए परिवर्तन आंतरिक कार्य कॉल में डी ... – GameAlchemist