Identification of a Collection of Arrays

My JSON data may have different formats. For example, it could look like this:

"coordinates":
  [
    [[100.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]],
    [[100.2,0.2],[100.8,0.2],[100.8,0.8],[100.2,0.8],[100.2,0.2]]
  ]

This format appears as an array of arrays and needs to be handled differently from something like this:

"coordinates":[30.0,10.0]

I was previously making decisions based on the length of the coordinates array (which is always 2 in these cases). However, I now need to ensure that it's not an array of arrays before taking certain actions.

Answer №1

Perhaps you could try implementing it this way?

if (Array.isArray(coordinates)) {
  // check if coordinates is an array
  if (Array.isArray(coordinates[0])) {
    // check if first element in coordinates is also an array
    // handle polyline data
  } else {
    // handle single point data
  }
}

Answer №2

But I want to ensure that it is not an array containing arrays

What if we create a simple check function:

var arr1=[1,2,3,4];
var arr2=[[1],[2]];

function checkArrayForArrays(arr){
    return arr.every(function(item){ return Array.isArray(item); });
}

console.log(checkArrayForArrays(arr1));
console.log(checkArrayForArrays(arr2));

JSBIN for testing. MDN documentation on Array.prototype.every().

Edit: Keep in mind that there may be cases where you have a mix of data types, which would result in false. In such scenarios, using Array.prototype.some() can help.

Answer №3

Consider the following:

bar = {"coordinates":[30.0,10.0]}

typeof bar.coordinates[0]
"number"

foo = {"coordinates":
  [
    [[100.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]],
    [[100.2,0.2],[100.8,0.2],[100.8,0.8],[100.2,0.8],[100.2,0.2]]
  ]}

typeof foo.coordinates[0]
"object"

Then you could proceed with:

foo = (parse your JSON data here)
if (typeof foo.coordinates[0] == "object") {
   // processing polyline
}
else {
   // handling point
}

Answer №4

This code snippet examines whether an array is a nested array:

let numbers = [10, 20, 30];
let nestedNumbers = [
  [1, 2, 3]
];

function checkArray(obj) {
  // In ES5 you could use obj.isArray
  return toString.call(obj) === "[object Array]";
}

function checkNestedArray(arr) {
  // Is it really an array?
  // If not, then it can't be a nested array
  if (!checkArray(arr)) {
    return false;
  }

  // Is the first element also an array?
  if (checkArray(arr[0])) {
    return true;
  }

  // Nope, not a nested array in this case
  return false;
}

console.log(checkNestedArray(numbers));
console.log(checkNestedArray(nestedNumbers));
console.log(checkNestedArray(null));

Answer №5

Is there a simple way to determine whether the item being processed is an array?

Array.isArray(coordinates[0]); can be used to check if the first element in the coordinates array is actually an array (assuming that coordinates points to the value of the coordinates property).

You could also verify if the first element is a number instead.

function arePointCoords(coords) {
    return Array.isArray(coords) && typeof coords[0] === 'number';
}


arePointCoords([30.0,10.0]); //true
arePointCoords([
    [[100.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]],
    [[100.2,0.2],[100.8,0.2],[100.8,0.8],[100.2,0.8],[100.2,0.2]]
]); //false

It's worth mentioning that using domain-specific names rather than technical terms like arePointCoords(coords) instead of !isArrayOfArrays(coords) can improve code readability. Nonetheless, arePointCoords may internally rely on a more general function like isArrayOfArrays.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Chrome's keyup event restricts the use of arrow keys in text fields

Could you please test this on Google Chrome browser: jQuery('#tien_cong').keyup(function(e) { jQuery(this).val(jQuery(this).val().replace(".", ",")); var sum = 0; var tien_cong = jQuery('#tien_cong').val(); tien_cong = tien_ ...

Transforming JSON information into selectable dropdown choices

Here is some data returned from an AJAX call that is now in JSON format: [{"PROCEDURE_ID":362183,"PROCEDURE_NAME":"Biopsy, Breast; Lumpectomy"}, {"PROCEDURE_ID":558975,"PROCEDURE_NAME":"Biopsy, Cervix"},{"PROCEDURE_ID":558977,"PROCEDURE_NAME":"Biopsy, int ...

The functionality of the click event does not function properly for buttons that are dynamically generated using

Upon selecting the "Keyboard layout" option, JavaScript generates buttons dynamically. However, the click event does not work with these dynamically generated buttons. This issue is likely due to the fact that the element ".prices-tier" does not exist when ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...

Update the navigation bar from displaying "LOGIN" to "LOGOUT

I am facing a challenge in updating the navbar login link to a logout link once the user logs in. I have attempted the following: header.ejs: <ul class="nav navbar-nav navbar-right"> <li id="home"><a href="/ ...

Having trouble with JQuery toggle()? Need some assistance with fixing it?

My attempts to utilize JQuery toggle functionality have been unsuccessful. The sliding up and down animation is not smooth and instead happens very quickly. I aim to achieve a sliding effect in my code similar to this example (Please refer to Website Des ...

Acquiring images from an external source and storing them in either the $lib directory or the static folder during the

Currently, I have a Sveltekit project set up with adapter-static. The content for my pages is being pulled from Directus, and my images are hosted in S3, connected to Directus for easy access. I am also managing audio samples in a similar manner. During b ...

Showing AJAX response on input fields

<table class="table table-bordered responsive"> <thead> <tr> <th>Session</th> <th>Bus Route</th> <th>Charges</th> <th> ...

Passing a 2D array to a function in C++ can be tricky, especially when dealing with undefined variables. Here's a guide

I am trying to figure out how to pass a 2D array to a function while maintaining the exact m & n variables that are defined in the int main(). This is an example of what I have: #include <iostream> using namespace std; void printBack(int b[][]); in ...

Adding an item to a non-existent observableArray in knockout

I am facing an issue within a viewmodel where I am attempting to dynamically add items to an observableArray. The ajax call is returning the data correctly. html : <li class="liTagulTagsChild" data-bind="click:$root.GetEmissions">/li> j ...

Getting the chosen value from a dropdown menu on form submission using PHP

How to Populate a Combo Box from a Database in PHP? <td>Item Name:</td> <td><select name="items"> <option value="0" selected="selected"> Choose</option> <?php while($row = mysql_fetch_ass ...

Experience screen sharing through WEBRTC without the need for any additional browser extensions

One question that I have is: Is it possible to implement screen sharing that works on a wide range of devices and browsers without the need for plugins or experimental settings? I have searched online and come across some plugins for Chrome, but I am look ...

Jackson does not seem to be registering the @JsonCreator annotation

I am currently working with Jackson 1.4.2 and facing an issue while trying to deserialize unique identifier values (referred to as `code`) that are sent from our UI to Java controllers (Servlets). We have various types (such as `ABCType`, `XYZType`, etc.) ...

How can I alter "diffuseMap" and "roughnessMap" in Three.js to become "cubeMap"?

I have a specific code snippet that I am trying to work with: var container; var camera, scene, renderer; let exrCubeRenderTarget, exrBackground; let newEnvMap; let torusMesh, planeMesh; var mouseX = 0, mouseY = 0; var windowHalfX = window.innerWi ...

Can the tooltip placement be adjusted in ng-bootstrap when it reaches a specific y-axis point?

Currently, I am facing an issue with my tooltip appearing under the header nav-bar instead of flipping to another placement like 'left-bottom' when it reaches the header. Is there a way to manually set boundaries for tooltips in ng-bootstrap? Unl ...

Issue encountered when attempting to develop a countdown timer using Typescript

I am currently working on a countdown timer using Typescript that includes setting an alarm. I have managed to receive input from the time attribute, converted it using .getTime(), subtracted the current .getTime(), and displayed the result in the consol ...

Sending data from JQuery Json to ASP.Net MVC results in both parameters being empty

After scouring through some old Q&A threads like this one on Stack Overflow, or checking out articles such as this one from Encosia and this post by West Wind... I've tried all the suggested tips and solutions, but still can't seem to g ...

Node.JS: Combining Multiple Files into a Single Output File

Currently, I am in the process of building a data pipeline using Node.js. While I acknowledge that there are better ways to approach this, I am determined to implement it and make improvements as I go. Here's the scenario: I have a collection of gzi ...

Utilizing `v-model` on a component that contains `<script setup>` in Nuxt can cause issues with the standard `<script>` tags

Working on a Nuxt3 project, I have implemented v-model on a component. Following the guidance from Vue documentation, here is how it should be done: In the parent component: <MyInput v-model="myData" placeholder="My placeholder" /&g ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...