Javascript Array组合元素以获得唯一的数组

时间:2017-03-28 05:56:55

标签: javascript arrays filter sum combiners

假设我有一个像这样的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中这样做的有效方法是什么?

3 个答案:

答案 0 :(得分: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; }




答案 1 :(得分:0)

您可以通过reduce对数组执行此操作,以形成从唯一[lat, lon]对到累积总weight的合并对象的地图。然后,您的结果就是该地图所持有的值列表(可以使用Object.keysArray#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%; }




答案 2 :(得分: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);