简体   繁体   English

排序对象数组不起作用

[英]Sorting an array of objects is not working

Sorting problem (I think I'm just messing up basic ES6 here, but am not seeing it): 排序问题(我认为我在这里只是弄乱了基本的ES6,但没有看到它):

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. 我有一个来自状态的绘图对象数组(实际上是两个数组之一,取决于是否已应用过滤器。)每个对象都有一个GeoJSON功能作为属性。 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. 在MapStateToProps中,我定义了一个函数,该函数返回绘图到地图中心的距离(已验证此方法可以正常工作),然后另一个函数复制绘图数组,按绘图到中心的距离排序,然后返回新数组。 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
    };
}

Within the .sort callback, you need to return the result: .sort回调中,您需要返回结果:

distancetoCenter(b, props) - distancetoCenter(a, props);

Should be: 应该:

return distancetoCenter(b, props) - distancetoCenter(a, props);

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)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM