[英]Sorting an array of objects is not working
排序問題(我認為我在這里只是弄亂了基本的ES6,但沒有看到它):
我有一個來自狀態的繪圖對象數組(實際上是兩個數組之一,取決於是否已應用過濾器。)每個對象都有一個GeoJSON功能作為屬性。 我也有一個來自州的地圖中心屬性。 在MapStateToProps中,我定義了一個函數,該函數返回繪圖到地圖中心的距離(已驗證此方法可以正常工作),然后另一個函數復制繪圖數組,按繪圖到中心的距離排序,然后返回新數組。 但是可悲的是,新數組未正確排序(無序)。
有人看到我想念的東西嗎?
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
};
}
在.sort
回調中,您需要返回結果:
distancetoCenter(b, props) - distancetoCenter(a, props);
應該:
return distancetoCenter(b, props) - distancetoCenter(a, props);
另一種解決方案是在箭頭函數中省略大括號。 然后返回表達式的結果。
return (props.filteredPlots || props.plots).slice(0).sort((a, b) =>
distancetoCenter(b, props) - distancetoCenter(a, props)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.