简体   繁体   中英

How to know if an array is single dimension or multiple dimension?

I need your help arround array in JS. I have a function where i need to check if the array passed in argument is one dimension or 2 dimension

let's say:

function test(array){
if(array is single dimension{
 console.log("Single dimension");
}else{
console.log("2Dimension");

and the following should display:

test([1,2,3]); // Should log "Single dimension"
test([[1,2,3],[1,2,3]]); // Should log "2Dimension"

Any help will be really nice! Thank you!

How to know if an array is single dimension or multiple dimension?

JavaScript doesn't have multi-dimensional arrays; it has arrays of arrays. There's a subtle difference between those two things. Even more, a JavaScript can have entries that are arrays and other entries that aren't arrays, making it only partially "multi-dimensional."

If you need to know that an array doesn't contain any arrays (eg, is one-dimensional), the only way is to check every entry in it to see if that entry is an array:

if (theArray.every(entry => !Array.isArray(entry)) {
    // One dimensional
} else {
    // Has at least one entry that is an array
}

Here's an example of an array that only has some entries that are arrays and others that aren't:

 const a = [1, 2, ["a", "b"], 3]; console.log(a.length); // 4, not 5 console.log(Array.isArray(a[0])); // false console.log(Array.isArray(a[2])); // true

You could take a recursive approach and check the first element for nested arrays.

 function getDimension([array]) { return 1 + (Array.isArray(array) && getDimension(array)); } console.log(getDimension([1, 2, 3])); console.log(getDimension([[1, 2, 3], [1, 2, 3]]));

Related to this one Get array's depth in JavaScript

You can use function like this one:

function getArrayDepth(value) {
  return Array.isArray(value) ? 
    1 + Math.max(...value.map(getArrayDepth)) :
    0;
}

Then simply

const testArray = [1,2,3];
if (getArrayDepth(testArray) > 1){
 console.log('One array');
}else{
  console.log('Array in array')
}

It can be checked like that:

 const arr = [1, 2, 3]; const multiDimensional = [ [1,2,3], [1,2,3] ]; const isMultiDimensional = (arr) => { const result = arr.reduce((a, c) => { if (c.constructor === Array) a = true; return a; }, false) return result; } console.log(isMultiDimensional ([1, 2, 3])); console.log(isMultiDimensional ([[1, 2, 3], [1, 2, 3]]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM