我有一个包含坐标的嵌套数组数组。我想根据它们是否具有相同的纬度来创建一个包含嵌套坐标数组的新数组。 描述可能有点困惑,所以这里有一些例子和代码
初始数组(纬度是数字对的第二个值)
const coordinateArray = [[46,11], [38,11], [44,9], [81,15], [55,15]];
预期结果:
const newArray = [
[[46,11],[38,11]],
[[81,15],[55,15]],
[[44,9]]
];
我试过了,但它返回一个新数组中的每个坐标,而不是将具有相同纬度的坐标配对:
const rowArrays = [];
coordinateArray.map(c => {
const row = [c];
for (let i = 0; i < coordinateArray.length; i++) {
console.log(c[1], coordinateArray[i][1]);
if (c[1] === [1]) {
row.push(coordinateArray[i]);
coordinateArray.splice(0, 1);
}
}
return rowArrays.push(row);
});
如有任何建议,将不胜感激
最佳答案
您的解决方案很接近,但正如您所提到的,它通过 coordinateArray
无条件地在每次迭代时创建一个新数组。因为您的输入到输出不是 1:1,而是您希望改变形状,所以 reduce
比 map
更可取。
如果你reduce
d 根据纬度将数组转换为对象,然后您可以使用 Object.values
以达到您想要的形状。
const coordinateArray = [[46,11], [38,11], [44,9], [81,15], [55,15]];
const matched = coordinateArray.reduce((out,arr) => {
out[arr[1]] = out[arr[1]] //Have we already seen this latitude?
? [arr, ...out[arr[1]]] //Yes: Add the current coordinates to that array
: [arr]; //No: Start a new array with current coordinates
return out;
}, {});
//const matched looks like this:
//{
// "9": [[44,9]],
// "11": [[38,11],[46,11]],
// "15": [[55,15],[81,15]]
//}
console.log(Object.values(matched)); //We only care about the values
如果您喜欢简洁和/或与您的开发人员同事有意见,可以使用扩展运算符 (...
) 将 reduce
转换为单个表达式) 和伪合并 (out[arr[1]] || []
)。
const coordinateArray = [[46,11], [38,11], [44,9], [81,15], [55,15]];
const matched = coordinateArray.reduce((out,arr) => ({...out, [arr[1]]: [arr, ...(out[arr[1]] || [])]}), {});
console.log(Object.values(matched));
关于javascript - 从 javaScript 数组中提取具有相同值的项目组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58012766/