2017-03-28 74 views
-2

假设我有一个JS数组是这样的:JavaScript数组相结合的元素获得一系列独特

[ 
    { 
    "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 
    } 
] 

假设我要添加了重量 S作相同LAT & 元素LON得到的东西是这样的:

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

什么是一个有效的方式做到这一点的JS?

+1

看Array.prototype.reduce,或者如果您发布到目前为止你已经尝试过的东西,我们可以进一步为您提供帮助。 – fubar

回答

0

您可以通过reduce做到这一点-ing您的阵列,形成从独特[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%; }

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

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