我们说我有一个包含状态及其余额的对象。
{
"amount": "822370.71",
"state": "ME"
},
{
"amount": "968817.53",
"state": "FL"
},
{
"amount": "587603.26",
"state": "OH"
},
{
"amount": "657617.83",
"state": "OH"
},
{
"amount": "657617.83",
"state": "FL"
}
我如何添加属于每个州的金额,例如OH将具有587603.26 + 657617.83。我相信map()方法将在这里使用,但我不知道如何使用它。谢谢!
答案 0 :(得分:2)
使用Array.prototype.forEach()
函数的简短解决方案:
var arr = [{"amount": "822370.71","state": "ME"},{"amount": "968817.53","state": "FL"},{"amount": "587603.26","state": "OH"},{"amount": "657617.83","state": "OH"},{"amount": "657617.83","state": "FL"}],
result = {};
arr.forEach(function (o) {
var amount = Number(o.amount);
(result[o.state])? result[o.state] += amount : result[o.state] = amount;
});
console.log(result);

答案 1 :(得分:1)
这是public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText number1 = (EditText) findViewById(R.id.number1);
final EditText number2 = (EditText) findViewById(R.id.number2);
Button add = (Button) findViewById(R.id.btnAdd);
Button sub = (Button) findViewById(R.id.btnSub);
Button div = (Button) findViewById(R.id.btnDiv);
Button mul = (Button) findViewById(R.id.btnMul);
final TextView txtresult = (TextView) findViewById(R.id.result);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1, num2, result;
num1 = Double.parseDouble(number1.getText().toString());
num2 = Double.parseDouble(number2.getText().toString());
result = num1 + num2;
txtresult.setText(Double.toString(result));
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1, num2, result;
num1 = Double.parseDouble(number1.getText().toString());
num2 = Double.parseDouble(number2.getText().toString());
result = num1 - num2;
txtresult.setText(Double.toString(result));
}
});
div.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1, num2, result;
num1 = Double.parseDouble(number1.getText().toString());
num2 = Double.parseDouble(number2.getText().toString());
result = num1 / num2;
txtresult.setText(Double.toString(result));
}
});
mul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double num1, num2, result;
num1 = Double.parseDouble(number1.getText().toString());
num2 = Double.parseDouble(number2.getText().toString());
result = num1 * num2;
txtresult.setText(Double.toString(result));
}
});
}
}
,filter
和map
一起使用的完美用例。
reduce