2016-10-03 11 views
0

配列内のいくつかのオブジェクト値を合計する必要があります。配列オブジェクトの文字列値の合計

JavaScriptを::私はthis methodを発見した

let array = [ 
{quantity: 1, amount: "24.99"} 
{quantity: 5, amount: "4.99"}, 
] 

は、スタックオーバーフローの周り掘り(イムが反応使用):他の人がstringすなわちすることができながら、いくつかは、intをすることができ

Array.prototype.sum = function (prop) { 
    var total = 0 
    for (var i = 0, _len = this.length; i < _len; i++) { 
     total += this[i][prop] 
    } 
    return total 
}; 

let totalQuantity = array.sum("quantity"); 
console.log(totalQuantity); 

ながらその作品素晴らしい、私は文字列amountのために同じことをする必要があります。 amountをfloatに変換する必要があるため、上記は機能しません。

Array.prototype.sum = function (prop) { 
    var newProp = parseFloat(prop); 
    var total = 0 
    for (var i = 0, _len = this.length; i < _len; i++) { 
     total += this[i][newProp] // Surely this is wrong :(
    } 
    return total 
}; 

これを達成するために、任意のきれいな方法:反応は、私は、これはいくつかの魔法を行うだろうと思った、およそComponent's children should not be mutated.

されていないJS忍者を不平を言いますか?

let totalAmount = array.sum("amount"); 

答えて

3

定義します

let array = [ 
 
{quantity: 1, amount: "24.99"}, 
 
{quantity: 5, amount: "4.99"} 
 
]; 
 
    
 
let sum = a => a.reduce((x, y) => x + y); 
 
    
 
let totalAmount = sum(array.map(x => Number(x.amount))); 
 
    
 
console.log(totalAmount.toFixed(2)) 
 
    
 

+0

良いキャッチ。私は 'Array.prototype'を使う代わりに別の方法があるのだろうかと思っていました。 – Sylar

2

てみてください:

私はこれが必要

Array.prototype.sum = function (prop) { 
    var total = 0 
    for (var i = 0, _len = this.length; i < _len; i++) { 
     total += parseFloat(this[i][prop]) // Surely this will work :) 
    } 
    return total 
}; 
+0

Ahhhhhhh!ありがとうございました。物を見るためにもう一度目を向けるのは良いことです。 – Sylar

+1

@Sylarはarray.reduceのバージョンを見てください;) –

0

const array = [ 
 
{quantity: 1, amount: "24.99"}, 
 
{quantity: 5, amount: "4.99"} 
 
] 
 
    
 
Array.prototype.sum = function(key) { 
 
    return this.reduce(function(total, item) { 
 
    return total + parseFloat(item[key]); 
 
    }, 0); 
 
} 
 

 
// weird javascript math ... 
 
console.log(array.sum("amount")); 
 

 
// workaround 
 
console.log(array.sum("amount").toFixed(2));

この作品罰金;)

0

私は通常reduce()方法を使用します。

let sum = a => a.reduce((x, y) => x + y); 

ほど自明であり、値のリストにそれを適用する汎用sum関数は、ソース・アレイから採取しましたこのような状況ではここにデモがあります:http://codepen.io/PiotrBerebecki/pen/zKEQgL

let array = [ 
{quantity: 1, amount: "24.99"}, 
{quantity: 5, amount: "4.99"} 
] 

function sumProperty(arr, type) { 
    return arr.reduce((total, obj) => { 
    if (typeof obj[type] === 'string') { 
     return total + Number(obj[type]); 
    } 
    return total + obj[type]; 
    }, 0); 
} 

let totalAmount = (sumProperty(array, 'amount')).toFixed(2); 
console.log( totalAmount ); // 29.98 

let totalQuantity = sumProperty(array, 'quantity'); 
console.log( totalQuantity ); // 6 
関連する問題