Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the dimensionality of a javascript array

What is the most efficient and/or most readable way to write a function that takes in an array and returns the degree of multi-dimensionality of that array. For now it can be assumed that the arrays only contain primitive types.

Example.

    var arr = [[1,2],[3,4],[5,6]]

    function findDim(a){
    //logic goes here
    }

    findDim(arr); // returns 2
like image 839
gilmatic Avatar asked Aug 30 '16 17:08

gilmatic


2 Answers

Use recursion and Array.isArray method to check element is an array.

var arr = [
  [1, 2],
  [3, 4],
  [5, 6]
];

function findD(arr) {
  // check the element is an array then do 
  // recursion to check it's element
  if (Array.isArray(arr)) {
    return 1 + findD(arr[0]);
  }
  // else return `0` since it's not
  // a nested array
  return 0;
}

console.log(findD(arr));

FYI : For older browser check polyfill option of Array.isArray method.


UPDATE : Incase it contains different dimensioned array and you want to get the deeper dimension then use Array#map and Math.max methods.

var arr = [
  [1, 2],
  [3, 4],
  [5, [6]]
];

function findD(arr) {
  // return 0 if not array else return the max value 
  // by finding all elements dimension
  return Array.isArray(arr) ?
    // generate the dimension value array 
    1 + Math.max.apply(Math, arr.map(findD)) : 0;
}

console.log(findD(arr));

Or with Array#reduce method to get the max value.

var arr = [
  [1, 2],
  [3, [4,[[3]]]],
  [5, [6]]
];

function findD(arr) {
  // return 0 if not array else return the max value 
  // by finding all elements dimension
  return Array.isArray(arr) ? 1 + arr.reduce(function(a, b) {
    // get the largest by comparing all the adjuscent 
    // elements dimension
    return Math.max(a, findD(b));
  }, 0) : 0;
}

console.log(findD(arr));
like image 158
Pranav C Balan Avatar answered Oct 02 '22 02:10

Pranav C Balan


"Dimensionality" is not well defined for js arrays (which are not necessary matrices), here's a function to find the max "depth" of the array:

maxDepth = x => Array.isArray(x)
  ? 1 + Math.max.apply(this, x.map(maxDepth))
  : 0
;

console.log(maxDepth([[1,2],[3,4],[5,6]]))
console.log(maxDepth([[[[1]]], 2]))
like image 30
georg Avatar answered Oct 02 '22 03:10

georg