javascript - Get the length of properties in a multidimensional array based on dimension? -
using vanilla javascript, want access length of multidimensional array based on "dimension" in.
example:
here's multidimensional array
var myarray = [a, b, c, d, [e, [f], g]] dimension 0 in has 5 elements [a, b, c, d, [e, [f], g]]
dimension 1 has 3 elements [e, [f], g]
dimension 2 has 1 element [f]
this have far (which isn't lot go off of - i'm stuck)
var getlength = function(arr, dimension) { subarray = []; (var e in arr) { if (e instanceof array) { return e.length } } } // getlength(myarray, 2) should equal 1 can kindly help?
you reduce , recurse while keeping track of arrays have been seen:
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}] then can find out total filtering collection depth , checking count. if sum counts work when have multiple arrays of same depth too:
var xs = [1, [2, 3], [4, 5, [6, 7]]] var count = depthcount(xs) console.log(count) // [{depth: 0, count: 3}, // {depth: 1, count: 2}, // {depth: 1, count: 3}, // {depth: 2, count: 2}] var counttotaldepth = function(depth, coll) { return coll.filter(function(obj) { return obj.depth === depth }).reduce(function(x, y) { return x.count + y.count }) } console.log(counttotaldepth(1, count)) // 5
Comments
Post a Comment