我有一个这样的多个数组:
var tree= ["es1“、null、" es11”、null、"info for es11“、"param for es11”、"es12“、null、"info for es12”、param for es12]、["es2“、null、" es21”、null、"info for es21“、"param for es21”、"es22“、"info for es22”、"param for es22“、"param for es22]
如果我想搜索"es22",我如何才能得到像tree[3][3][0]这样的职位?我试过这样做:
function recursion(obj,strs){
if (found) return;
for(var j=0;j<obj.length;j++){
c++;
if (isArray(obj[j])&&!found) {
recursion(obj[j],strs);
} else {
if (obj[j]==strs&&!found) {
arr=obj;
found=true;
return;
}
}
}发布于 2017-12-20 11:40:02
每当找到项目时,返回index,并在它之前追加所有以前的索引:
var tree=["root",null,["es1",null,["es11",null,"info for es11","param for es11"],["es12",null,"info for es12","param for es12"]],["es2",null,["es21",null,"info for es21","param for es21"],["es22",null,"info for es22","param for es22"]]];
function recursion(arr, str, indexes) {
var result;
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = recursion(arr[i], str, indexes);
if(result !== null) {
return [i].concat(result);
}
} else if(arr[i] === str) {
return i;
}
}
return null;
}
console.log(recursion(tree, "es22", []));
发布于 2017-12-20 12:29:34
这是我的尝试..。
var tree = [
"root",
null,
["es1", null, ["es11"], ["es12"]],
["es2", null, ["es21"], ["es22"]]
];
const find = (subtree, item, path = []) => Array.isArray(subtree)
? subtree.some((e, i) => (find(e, item, path) && path.unshift(i))) && path
: subtree === item;
console.log(find(tree, 'es22'));
描述:
深度优先搜索。如果subtree是数组,则枚举。对于每个元素,首先对该子树执行深度搜索。
如果subtree是item,则返回true。这将导致堆栈展开。在每个堆栈帧中,如果子树搜索成功,则将当前数组索引添加到path的前面。
如果在子树中找到path,则将item传递到堆栈帧链中。
当完成时,如果找到元素,则返回path,其中包含元素的索引,否则返回false。
伪码:
def solution(subtree, item, path)
if subtree is not an array
return subtree is item
else
for each index, value in subtree
var found = solution(value, item, path)
if found
add index to path
return path
end if
end for
end if
end def发布于 2017-12-20 11:49:48
希望它有帮助:
:
function findPosition(search, neddle) {
for (let i = 0; i < search.length; i++) {
if (search[i] === neddle) {
return [i];
} else if (Array.isArray(search[i])) {
const match = findPosition(search[i], neddle);
if (match.length > 0) {
return [i].concat(match);
}
}
}
return [];
}
和测试:
// findPosition TEST
const tree = [
"root",
null,
[
"es1",
null,
["es11", null, "info for es11", "param for es11"],
["es12", null, "info for es12", "param for es12"]
],
[
"es2",
null,
["es21", null, "info for es21", "param for es21"],
["es22", null, "info for es22", "param for es22"]
]
];
const expected = [3, 3, 0].join(',');
const actual = findPosition(tree, 'es22').join(',');
if (actual === expected) {
console.log('pass');
} else {
console.log('fail');
console.log(actual, 'not equal to', expected)
}
https://stackoverflow.com/questions/47904865
复制相似问题