-1

我有一个array这样的对象:

[
  {
    latitude: 00,
    longitude: 11
  },
  {
    latitude: 22,
    longitude: 33
  },
  {
    latitude: 00,
    longitude: 11
  }, 
]

我想将该数组转换并过滤为另一个数组,该数组包含数组,其中包含对象:

如果经度和纬度相等,它们应该去同一个数组,所以,我需要一个像这样的新数组:

[
  [
    {
      latitude: 00,
      longitude: 11
    },
    {
      latitude: 00,
      longitude: 11
    }
  ],
  [
    {
      latitude: 22,
      longitude: 33
    }
  ]
]
4

6 回答 6

4

reduce放入一个对象,其键表示数组对象的内容,其值是数组,然后创建/推送到适当的数组:

const input=[{latitude:00,longitude:11},{latitude:22,longitude:33},{latitude:00,longitude:11},]
const output = Object.values(
  input.reduce((a, obj) => {
    const key = JSON.stringify(obj);
    if (!a[key]) a[key] = [];
    a[key].push(obj);
    return a;
  }, {})
)
console.log(output);

于 2018-05-21T08:57:40.850 回答
2

如果您两次发现相同的元素,我建议您在JSON对象添加更新中添加计数字段,count否则上述答案看起来不错。

var data = [{
        latitude: 00,
        longitude: 11
    },
    {
        latitude: 22,
        longitude: 33
    },
    {
        latitude: 00,
        longitude: 11
    },
]
var result = [];
data.forEach(val => {
    const filterIndex = result.findIndex(v => v.latitude == val.latitude && v.longitude == val.longitude);
    filterIndex == -1 ? result.push({ ...val,
        count: 1
    }) : result[filterIndex].count += 1;
});
console.log(result);

于 2018-05-21T09:10:26.407 回答
1

您可以使用latitudeandlongitude创建唯一键,并为对象累加器中的每个唯一键推送数组中的每个对象。然后使用Object.values()提取所有值。

const data = [ { latitude: 00, longitude: 11 }, { latitude: 22, longitude: 33 }, { latitude: 00, longitude: 11 }, ],
    result = Object.values(data.reduce((r,{latitude, longitude}) => {
      const key = latitude + '_' + longitude;
      r[key] = r[key] || [];
      r[key].push({latitude, longitude});
      return r;
    },{}));
console.log(result);

于 2018-05-21T08:56:27.840 回答
1

您可以将您的数组简化为一个对象,其经纬度形成一个唯一键,并推送与其对应的值。然后使用 Object.values 取回数组

尝试关注

var arr = [ { latitude: 00, longitude: 11 }, { latitude: 22, longitude: 33 }, { latitude: 00, longitude: 11 }];

var map = arr.reduce((a,c) => {
var key = c.latitude + "_" + c.longitude;
  a[key] = a[key] || [];
  a[key].push(c);
  return a;
}, {});

console.log(Object.values(map));

供参考,Array.reduceObject.values

于 2018-05-21T08:56:42.967 回答
1

您可以对哈希表使用组合键来加速重复查找:

 const result = [], hash = {};

 for(const {latitude, longitude} of array) {
   const key = latitude + "_" + longitude;
   if(hash[key]) {
     hash[key].push({longitude, latitude});
   } else {
     result.push(hash[key] = [{longitude, latitude}]);
   }
 }
于 2018-05-21T09:32:46.080 回答
1

这是过滤的解决方案,首先您减少分组数据,然后连接到字符串。

    var a = [{latitude:21,longitude:12},{latitude:211,longitude:2},];

    var mapped = a.reduce((acc, e) => {
        var key = '' +  e.latitude + ','+ e.longitude;
        if (!acc[key])  acc[key] = [e];
        else acc[key].push(e);	
       return acc;
    }, {});

    console.log(Object.keys(mapped).map((key) => mapped[key]));

    // edit
    console.log(Object.values(mapped));
    

于 2018-05-21T09:02:34.110 回答