Reputation: 3580
Sorting problem (I think I'm just messing up basic ES6 here, but am not seeing it):
I've got an array of plot objects coming in from state (actually, one of two arrays, depending on whether filters have been applied.) Each object has a GeoJSON feature as a property. I also have a map center property coming in from state. In MapStateToProps, I define a function which returns a plot's distance from the center of the map (verified that this works properly), then another which copies the plot array, sorts plots by their distance from the center, then returns the new array. But sadly, the new array is not sorted properly (no order to it.)
Does anyone see what I'm missing?
function mapStateToProps(state) {
const distancetoCenter = (shape, props) => {
if (shape.feature && props.mapCenter) {
const theDistance = distance(
centroid(shape.feature).geometry.coordinates.reverse(),
point([props.mapCenter.lat, props.mapCenter.lng]),
{ units: 'kilometers' }
);
//console.log(`the distance to center of ${shape.name} is ${theDistance}`);
return theDistance;
}
};
const sortPlots = props => {
if (props.filteredPlots || props.plots) {
return (props.filteredPlots || props.plots).slice(0).sort((a, b) => {
distancetoCenter(b, props) - distancetoCenter(a, props);
});
}
};
const sortedPlots = sortPlots(state.plots);
return {
mapCenter: state.plots.mapCenter,
sortedPlots
};
}
Upvotes: 1
Views: 90
Reputation: 386540
An other solution could be to omit the curly brackets in an arrow function. Then the result of the expression is returned.
return (props.filteredPlots || props.plots).slice(0).sort((a, b) =>
distancetoCenter(b, props) - distancetoCenter(a, props)
);
Upvotes: 2
Reputation: 31963
Within the .sort
callback, you need to return the result:
distancetoCenter(b, props) - distancetoCenter(a, props);
Should be:
return distancetoCenter(b, props) - distancetoCenter(a, props);
Upvotes: 2