我想将所有的子数组放在一个嵌套数组中,在每个深度之外创建一个新的数组(包括原始输入数组),并将它们放入一个新的数组中。
输入:
var array = ["cat", ["dog", ["rabbit"]], "hamster"]
输出:
newArray = [
["cat", ["dog", ["rabbit"]], "hamster"],
["dog", ["rabbit"]],
["rabbit"]
]
尝试:
var unnest = function(array) {
var container = [array];
for (var i in array) {
if (array[i] instanceof Array) {
container.push(array[i]);
}
}
return container
}
我知道这需要某种迭代或递归过程,但这就是我被困住的地方(我是JavaScript的新手)。谢谢。
发布于 2015-06-02 04:45:21
你就快到了!您只需要更改一件事:将for循环包装在一个函数中,以便可以递归地调用它。这里有一个这样做的方法。
var unnest = function(array) {
var container = [array];
var collectNestedArrays = function(array) {
array.forEach(function(x) {
if (x instanceof Array) {
container.push(x);
collectNestedArrays(x);
}
});
};
collectNestedArrays(array);
return container;
};
发布于 2015-06-02 04:45:28
因为我们迭代一个数组并为父数组和树中的每个子数组创建元素,所以这个问题最好用递归DFS算法来解决。
function unnest(src) {
// overload the parameters and take the target array as a second argument.
// this helps us avoid having nested functions, improve performance
// and reduce boilerplate
var target = arguments[1] || [];
// add the current array to the target array
target.push(src);
// iterate on the parent array and recursively call our function,
// assigning the child array, and the target array as function parameters
src.forEach(function (node) {
if (node instanceof Array) {
unnest(node, target);
}
});
return target;
}
发布于 2015-06-02 04:46:39
下面是一个递归实现。
var unNest = function(array) {
// Create a results array to store your new array
var resultsArr = [];
// Recursive function that accepts an array
var recurse = function(array) {
// Push the passed-in array to our results array
resultsArr.push(array);
// Iterate over the passed-in array
for (var i = 0; i < array.length; i++) {
// If an element of this array happens to also be an array,
if (Array.isArray(array[i])) {
// Run the recursive function, passing in that specific element which happens to be an array
recurse(array[i]);
}
}
}
// Invoke our recurse function, passing in the original array that unNest takes in
recurse(array);
// Return the results array
return resultsArr;
}
https://stackoverflow.com/questions/30587355
复制