Home > Back-end >  How to sort an array by an object with 2 properties based on a different array
How to sort an array by an object with 2 properties based on a different array

Time:12-02

I have 2 arrays.

First array looks like this:

const array1 = [
 {lon: -79.458321, lat: 43.86681, layer: NewClass},
 {lon: -79.4552519, lat: 43.8111705, layer: NewClass},
 {lon: -79.4583686, lat: 43.7910661, layer: NewClass},
 {lon: -79.4757382, lat: 43.7843178, layer: NewClass},
 ...
 ...
 ...
]

The other array looks like this:

const array2 = [
 {coordinates: {lat: 43.63955, lng: -79.38959}},
 {coordinates: {lat: 43.7197383, lng: -79.4317488}},
 {coordinates: {lat: 43.6559076, lng: -79.4547443}}
 ...
 ...
 ...
]

How would I go about sorting array2 based on the long & lat properties in array1?

CodePudding user response:

Wouldn't the easiest way be to just do the following.

const array1 = array2.map(c => {lat: c.coordinates.lat, lon: c.coordinates.long});

And otherwise if you want to keep your layer it would be something like

const array3 = array2.map(c => array1.find(d => d.long == c.coordinates.lng && d.lat == c.coordinates.lat));
  • Related