gpt4 book ai didi

javascript - 对对象数组进行排序不起作用

转载 作者:行者123 更新时间:2023-11-30 09:28:24 26 4
gpt4 key购买 nike

排序问题(我想我只是在这里弄乱了基本的 ES6,但我没有看到它):

我有一组来自状态的绘图对象(实际上,是两个数组之一,具体取决于是否应用了过滤器。)每个对象都有一个 GeoJSON 特性作为属性。我还有一个来自州的 map 中心属性。在 MapStateToProps 中,我定义了一个函数,该函数返回绘图与 map 中心的距离(已验证这是否正常工作),然后另一个函数复制绘图数组,按绘图与中心的距离对绘图进行排序,然后返回新数组。但遗憾的是,新数组没有正确排序(没有顺序)。

有人看到我遗漏了什么吗?

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

关于javascript - 对对象数组进行排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com