简化版
for ...
ar = [
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
应该返回......
ans = [[
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4}],
[{"element":"a","index":0},
{"element":"b","index":1},
{"element":"d","index":3}]
];
它可以返回只有{“element”:“e”,“index”:4}和{{element“:”d“,”index“:3}的数组,因为它背后没有任何东西,但它是没必要。
原始 我有这个元素阵列......
ar = [
{"element":"c","index":2},
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
我想返回一个数组数组,其中包含每个对象的“索引”逐渐增长的序列,并且具有obj1[index] < nextobj[index]
的最大对象数。
即。它应该返回..
[
[{"element":"c","index":2}, {"element":"e","index":4}],
[{"element":"c","index":2}, {"element":"d","index":3}],
[{"element":"a","index":0}, {"element":"b","index":1}, {"element":"d","index":3}],
[{"element":"a","index":0}, {"element":"b","index":1}, {"element":"e","index":4}]
[{"element":"d","index":3}],
[{"element":"e","index":4}]
]
我尝试过使用ar.reduce,但对它并不熟悉,也不知道它是否适用于此实例。
答案 0 :(得分:1)
不确定为什么这些未在您的示例中列出
[{ element="a", index=0}, { element="e", index=4}]
[{ element="a", index=0}, { element="d", index=3}]
[{ element="b", index=1}, { element="e", index=4}]
[{ element="b", index=1}, { element="d", index=3}]
但是这可以产生一些接近的东西
var ar = [
{"element":"c","index":2},
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
var results = [];
traverse([], 0);
function traverse(r, startIdx)
{
if (startIdx >= ar.length){
console.log(r);
return;
}
for (var i = startIdx; i < ar.length ; i++){
if ((startIdx == 0) || (r[r.length - 1].index) <= ar[i].index) {
rCopy = r.slice(0);
rCopy.push(ar[i]);
traverse(rCopy, i + 1);
}
else if (r.length > 0) {
console.log(r);
}
}
}
var ar = [
{"element":"c","index":2},
{"element":"a","index":0},
{"element":"b","index":1},
{"element":"e","index":4},
{"element":"d","index":3}
];
var results = [];
traverse([], 0);
collapse(results);
//console.log(results);
for (var i = results.length - 1; i >= 0; i--) {
console.log(results[i]);
}
function traverse(r, startIdx) {
if (startIdx >= ar.length) {
results.push(r);
return;
}
for (var i = startIdx; i < ar.length ; i++) {
if ((startIdx == 0) || (r[r.length - 1].index) <= ar[i].index) {
rCopy = r.slice(0);
rCopy.push(ar[i]);
traverse(rCopy, i + 1);
}
else if (r.length > 0) {
results.push(r);
}
}
}
function collapse() {
for (var i = results.length - 1; i >= 0; i--) {
for (var j = results.length - 1; j >= 0; j--) {
if ((i !== j) && (contains(results[i], results[j]))) {
results[i].remove = true;
}
}
}
for (var i = results.length - 1; i >= 0; i--) {
if (results[i].remove) {
results.splice(i, 1);
}
}
}
// Checks if set1 is contained within set2
function contains(set1, set2) {
for (var i = 0; i < set1.length; i++) {
var found = false;
for (var j = 0; j < set2.length; j++) {
if (set1[i].index === set2[j].index) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}