Javascript 对对象数组排序不起作用
排序问题(我想我只是搞乱了基本的ES6,但我没有看到): 我有一个来自state的plot对象数组(实际上是两个数组中的一个,取决于是否应用了过滤器)。每个对象都有一个GeoJSON特性作为属性。我也有一个地图中心的财产来自国家。在MapStateToProps中,我定义了一个函数,该函数返回一个绘图到地图中心的距离(验证该函数是否正常工作),然后是另一个函数,该函数复制绘图数组,根据绘图到中心的距离对其进行排序,然后返回新数组。但遗憾的是,新数组没有正确排序(没有顺序) 有人看到我遗漏了什么吗Javascript 对对象数组排序不起作用,javascript,sorting,Javascript,Sorting,排序问题(我想我只是搞乱了基本的ES6,但我没有看到): 我有一个来自state的plot对象数组(实际上是两个数组中的一个,取决于是否应用了过滤器)。每个对象都有一个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,道具)-distancetoCenter(a,道具)代码>
应该是:
返回距离中心(b,道具)-距离中心(a,道具)
在.sort
回调中,您需要返回结果:
distancetoCenter(b,道具)-distancetoCenter(a,道具)代码>
应该是:
返回距离中心(b,道具)-距离中心(a,道具)代码>另一种解决方案是省略一个表中的花括号。然后返回表达式的结果
return (props.filteredPlots || props.plots).slice(0).sort((a, b) =>
distancetoCenter(b, props) - distancetoCenter(a, props)
);
另一个解决方案是省略一个表中的花括号。然后返回表达式的结果
return (props.filteredPlots || props.plots).slice(0).sort((a, b) =>
distancetoCenter(b, props) - distancetoCenter(a, props)
);
您在state.plots上调用sortPlots,而不是仅在state.plots上调用。@brub这是应该的方式,因为这些数组位于state.plots中。您在state.plots上调用sortPlots,而不是仅在state.plots上调用sortPlots。@brub这是应该的方式,因为这些数组位于state.plots中。