4

我有一个包含坐标的嵌套数组数组。我想创建一个包含嵌套坐标数组的新数组,基于它们是否具有相同的纬度。描述可能有点混乱,所以这里有一些示例和代码

初始数组(纬度是数字对的第二个值)

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

将不胜感激任何建议

4

3 回答 3

4

您的解决方案很接近,但正如您所提到的,它无条件地在每次迭代时创建一个新数组coordinateArray。因为您的输入到输出不是 1:1,而是您希望更改形状,reduce所以最好使用map.

如果您reduce根据纬度将数组转换为对象,则可以使用它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));

于 2019-09-19T14:05:15.810 回答
0

创建地图和组:

const coordinateArray = [[46,11], [38,11], [44,9], [81,15], [55,15]];
let map = coordinateArray.reduce((map,coord)=>{
  map.has(coord[1]) ? map.get(coord[1]).push(coord) : map.set(coord[1], [coord]);
  return map;
},new Map())
console.info([...map.values()])

于 2019-09-19T14:09:18.960 回答
0

肯定有更好的方法可以用上面发布的更少的代码行来编写它,但这可能会让您更容易理解:

const coordinateArray = [[46,11], [38,11], [44,9], [81,15], [55,15]];

const rowArrays = [];

coordinateArray.forEach(c => {
    // set match to false at the beginning of every new coordinate
    let match = false;
    rowArrays.forEach (r => {
      // check if your coordinate lattitude already exists in rowArrays
      // if it does, push it to that array, and set match to true
      if (r[0][1] === c[1]) {
        r.push(c);
        match = true;
      }
    });
    // after iterating through every item in rowArrays, if you still
    // haven't found a match, push the new array to rowArrays.
   if(!match){
    rowArrays.push([c])
   }
  });

console.log(rowArrays)

于 2019-09-19T14:25:00.680 回答