Search code examples
looker-studiodeck.gl

JavaScript, find lowest value in array of objects


I am building a custom visual using deckgl, here is the code and the whole visual

datastudio.google.com/reporting/fe15b7b1-aa4a-4f1b-9b29-52db4734c526

currently, I am just using the first element as a reference for the initial view

var data1 = DEFAULT;
var firstvalue = data1[0].coordinateid.toString();
var coordinates = firstvalue.split(",");
var longitudeView =parseFloat(coordinates[0]);
var latitudeView =parseFloat(coordinates[1]);

here an example of array of objects I am using

"DEFAULT": [
      {
        "coordinateid": [
          "140,-34.777302"
        ],
        "colorid": [
          "169,255,169"
        ],
        "sizeid": [
          31
        ]
      },
      {
        "coordinateid": [
          "143.4999358,-34.77"
        ],
        "sizeid": [
          150
        ]
      },
      {
        "coordinateid": [
          "143.4999381,-20"
        ],
        "colorid": [
          "169,169,169"
        ],
        "sizeid": [
          1900
        ]
      }
    ]

how to get the lowest values for the field "coordinateid" , in this example is [140,-20] I am new to javascript, I do understand how to access individual object values, But not sure how to loop through the whole array, is there a function to access directly all the values of the field "Coordinateid" or should I use a loop.


Solution

  • You have 2 options:

    1. the faster one- a simple loop where you always keep the lowest one you found so far:

      let lowest = arr[0];
      for(let i=1; i<0; i++)
      {
          if(arr[i] < lowest) // I used < for the example, enter your comparison logic here
           lowest = arr[i];
      }
      
    2. The less efficient way, but might help you later in your code: sorting the array using 'Array.sort' method:

      array.sort( (el1, el2) => {
        if(el1 > el2) // again- I used > sign, put the actual comparison logic here, i.g: el1.coordinateid[0] > el2.coordinateid[0] and so on
          return -1;
        else return 1;
      });
      

    Note that the sort array work like that: you give it a callback function which gets 2 elements of the array. If you return -1 it means the first element that passed should come before the 2nd element when they are put back in the sorted array, 0 means they're equal and 1 means that the 2nd element passed to the function should come first. See the sort method link above for more explanation.