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

Time:10-26

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/

CodePudding user response:

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)

CodePudding user response:

u can make a temp var

let arr = []
polylineTimestamp.forEach((el) => {
  arr.push([el[0],el[1]])
})
console.log(arr)
//! expected output would be
arr = [
  [ 37.781814, -122.40474 ],
  [ 37.781719, -122.404637 ],
  [ 37.781489, -122.404949 ],
  [ 37.780704, -122.403945 ],
  [ 37.780012, -122.404827 ]
]

you also can get a new arr the it can filter to not get the index 2 from the origin arr

CodePudding user response:

Here is your answerer:

const TIMESTAMP_POSITION = 2
var polylineTimestamp = [
    [37.781814, -122.404740, 1666540000],
    [37.781719, -122.404637, 1666541000],
    [37.781489, -122.404949, 1666542000],
    [37.780704, -122.403945, 1666543000],
    [37.780012, -122.404827, 1666544000]
];
polylineTimestamp.sort(function (a, b) {
    // Turn your timestamp number into dates, and then subtract them
    // to get a value that is either negative, positive, or zero.
    return new Date(b[TIMESTAMP_POSITION]) - new Date(a[TIMESTAMP_POSITION]);
})
//map to remove timestamp
var polyLineArray = polylineTimestamp.map(function (polyLine) {
    return [polyLine[0], polyLine[1]]
})

I used the sort function to sort your initial array using date conversion from timestamp.

when just mapping the array to remove the timestamp

  • Related