Search code examples
javascriptarrayssortingleaflet

How to sort array in JS for Leaflet map and then trim


I need to have in array with lat/lon points like that:

/*
var polylinePoints = [
    [37.781814, -122.404740],
    [37.781719, -122.404637],
    [37.781489, -122.404949],
    [37.780704, -122.403945],
    [37.780012, -122.404827]
  ]; 
  */

But I need first to sort it by third parameter which is timestamp? How to do that? I know how to do that in PHP but not in JS

var polylineTimestamp = [
    [37.781814, -122.404740, 1666543938],
    [37.781719, -122.404637, 1666543938],
    [37.781489, -122.404949, 1666543938],
    [37.780704, -122.403945, 1666543938],
    [37.780012, -122.404827, 1666543938]
  ]; 

Then I need to delete (trim) sorted array (delete timestamp) to have something like polylinePoints.

Here is Jsfiddle: https://jsfiddle.net/qsdaLz7h/


Solution

  • Array .sort() and .map() will get you there. You could combine them, but it'll be easier for you to follow the logic when they're separated, as below.

    // I changed your original timestamps to give some difference
    var polylineTimestamp = [
        [37.781814, -122.404740, 1666543958],
        [37.781719, -122.404637, 1666543948],
        [37.781489, -122.404949, 1666543968],
        [37.780704, -122.403945, 1666543938],
        [37.780012, -122.404827, 1666543998]
      ]; 
    
    // sort polylineTimestamp by third parameter (timestamp) older first
    var sortedarray = polylineTimestamp.sort((a,b)=> {
        return a[2] - b[2];
    });
    
    // Remove timestamp from resulting array
    var polylinePoints = sortedarray.map(el => {
        return [el[0],el[1]];
    });
    
    // Log to console
    console.log(polylinePoints)