根据维度获取多维数组中的属性长度?

时间:2015-05-31 03:46:55

标签: javascript arrays recursion multidimensional-array

使用vanilla JavaScript,我想根据它所在的“维度”访问多维数组的长度。

示例:

这是一个多维数组

  var myArray = [a, b, c, d, [e, [f], g]]

尺寸0 in有5个元素[a, b, c, d, [e, [f], g]]

尺寸1有3个元素[e, [f], g]

尺寸2有1个元素[f]

这就是我到目前为止所做的事情(这不是很重要 - 我真的被卡住了)

var getLength = function(arr, dimension) {
  subarray = [];
  for (var e in arr) {
    if (e instanceof Array) {  
     return e.length
    }
  }
}

// getLength(myArray, 2) should equal 1

你能帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以在跟踪已看到的数组时减少并递归:

.count

然后你可以通过深度过滤集合并检查计数来找出总数。如果总结计数,当你有多个相同深度的数组时它也会起作用:

var depthCount = function(xss, depth) {
  depth = depth || 0
  var seen = []
  return xss.reduce(function(acc, xs) {
    if (Array.isArray(xs)) {
      return acc.concat(depthCount(xs, depth + 1))
    }
    if (seen.indexOf(xss) < 0) {
      seen.push(xss)
      return acc.concat({depth: depth, count: xss.length})
    }
    return acc
  }, [])
}

var xs = [1, 2, 3, 4, [5, [6], 7]]

console.log(depthCount(xs))
// [{depth: 0, count: 5},
//  {depth: 1, count: 3},
//  {depth: 2, count: 1}]

答案 1 :(得分:1)

您可以使用辅助方法递归获取成员数,然后使用main方法只使用&#34; layer&#34;

来访问所需的图层数。

辅助函数的伪代码:

// Count members, and store if object
// Recursively get list of lengths from those objects
// Sum up those lists
    // find length of longest array
    // sum up all values, up to length of longest array
// Insert 'count' at front of the list
// Return

完整代码:

/*
Main function
Returns a number: the count of members in a layer
*/
function getLength(layer, obj)
{
    return getAllLengths(obj)[layer];
}



/*
Helper function for getLength(..)
Returns an array
*/
function getAllLengths(obj)
{
    var count = 0; // for this layer's # of members
    var objectMembers = []; // list of members that are objects
    var objectsLists = []; // to store list of lists produced recursively from objectMembers
    var result = []; // to return


    // count, and store if object
    for (var mem in obj)
    {
        count++;
        if (obj[mem] instanceof Object)
        {
            objectMembers.push(obj[mem] );
        }
    }


    // recursively get objects' lists
    for (var i in objectMembers)
    {
        objectsLists.push(getAllLengths(objectMembers[i] ));
    }


    ////// sum up lists
    // find length of longest array
    var maxLength = 0;
    for (var i in objectsLists)
    {
        if (objectsLists[i].length > maxLength)
        {
            maxLength = objectsLists[i].length;
        }
    }
    // sum
    for (var i = 0; i < maxLength; i++)
    {
        var sum = 0;
        for (var j = 0; j < objectsLists.length; j++)
        {
            if (objectsLists[j][i] != undefined)
                sum += objectsLists[j][i];
        }
        result.push(sum);
    }


    // complete resulting list to return
    result.splice(0,0, count);

    return result;
}