-2

假设我有一个这样的 JS 数组:

[
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 120
  },
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 80
  },
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 160
  },
  {
    "lat": 49.26229,
    "lon": 23.24342,
    "weight": 236
  },
  {
    "lat": 49.26229,
    "lon": 23.24342,
    "weight": 167
  }
]

假设我想将具有相同lat & lon的元素的权重相加得到如下结果:

[
  {
    "lat": 49.26125,
    "lon": -123.24807,
    "weight": 360
  },
  {
    "lat": 49.26229,
    "lon": 23.24342,
    "weight": 403
  }
]

什么是在 JS 中做到这一点的有效方法?

4

3 回答 3

0

您可以将哈希表用作闭包,并将键与latlon作为组合值。

然后检查哈希是否存在,如果不存在,则使用数据生成一个新对象并将其推送到结果集。

稍后添加weight到散列对象的属性。

var data = [{ lat: 49.26125, lon: -123.24807, weight: 120 }, { lat: 49.26125, lon: -123.24807, weight: 80 }, { lat: 49.26125, lon: -123.24807, weight: 160 }, { lat: 49.26229, lon: 23.24342, weight: 236 }, { lat: 49.26229, lon: 23.24342, weight: 167 }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var key = ['lat', 'lon'].map(function (k) { return a[k]; }).join('|');
            if (!hash[key]) {
                hash[key] = { lat: a.lat, lon: a.lon, weight: 0 };
                r.push(hash[key]);
            }
            hash[key].weight += a.weight;
            return r;
        };
    }(Object.create(null)), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2017-03-28T06:04:08.763 回答
0

你可以做这样的事情。它可能效率不高,但它确实有效。

var arr = [{ lat: 49.26125, lon: -123.24807, weight: 120 }, { lat: 49.26125, lon: -123.24807, weight: 80 }, { lat: 49.26125, lon: -123.24807, weight: 160 }, { lat: 49.26229, lon: 23.24342, weight: 236 }, { lat: 49.26229, lon: 23.24342, weight: 167 }];

arr = arr.reduce(function(accumulation, currentElement){
    var samePosition = accumulation.find(function(obj){
        return obj.lat === currentElement.lat && obj.lng === currentElement.lng;
    });
    if(samePosition){
        samePosition.weight += currentElement.weight;
    }else{
        accumulation.push(currentElement);
    }
    return accumulation;
}, []);

console.log(arr);

于 2017-03-28T06:10:20.600 回答
0

您可以通过reduce-ing 您的数组以形成从唯一[lat, lon]对到合并对象的映射来完成此操作,该对象累积您的总数weight。然后,您的结果就是该映射所持有的值列表(可以使用Object.keysand获得Array#map)。

var array = [{lat:49.26125,lon:-123.24807,weight:120},{lat:49.26125,lon:-123.24807,weight:80},{lat:49.26125,lon:-123.24807,weight:160},{lat:49.26229,lon:23.24342,weight:236},{lat:49.26229,lon:23.24342,weight:167}]

var map = array.reduce(function (map, o) {
  var k = [o.lat, o.lon].join()
  
  if (k in map)
    map[k].weight += o.weight
  else 
    map[k] = o
  
  return map
}, {})

var result = Object.keys(map).map(function (k) { return map[k] })

console.log(result)
.as-console-wrapper { min-height: 100%; }

于 2017-03-28T06:05:00.157 回答