获取javascript

时间:2016-03-30 20:55:04

标签: javascript

我有以下数组:

route: [
  {
    flyFrom: "CDG",
    flyTo: "DUB",
    return: 0,
  },
  {
    flyFrom: "DUB",
    flyTo: "SXF",
    return: 0,
  },
  {
    flyFrom: "SFX",
    flyTo: "CDG",
    return: 1,
  }
]

我需要计算返回的次数:0以及返回的次数:1。

最终结果如下:

对于返回的情况:0出现2次--- 1次停止

对于返回的情况:1出现1次---不间断

5 个答案:

答案 0 :(得分:3)

您可以使用Array.prototype.filter()过滤01值,并检查结果的长度(ES6语法):

var route = [
    { flyFrom: 'CDG', flyTo: 'DUB', return : 0, },
    { flyFrom: 'DUB', flyTo: 'SXF', return : 0, },
    { flyFrom: 'SFX', flyTo: 'CDG', return : 1, }
];

var zeros = route.filter(r => r.return === 0).length;
var ones = route.filter(r => r.return === 1).length;

ES5类比:

var zeros = route.filter(function(r) {
    return r.return === 0;
}).length;

另一种解决方案是减少数组:

var zeros = route.reduce((a, b) => a + (b.return === 0), 0);

答案 1 :(得分:0)

您可以使用单个循环迭代并计算对象中的返回值。

var data = { route: [{ flyFrom: "CDG", flyTo: "DUB", 'return': 0, }, { flyFrom: "DUB", flyTo: "SXF", 'return': 0, }, { flyFrom: "SFX", flyTo: "CDG", 'return': 1 }] },
    count = {};

data.route.forEach(function (a) {
    count[a.return] = (count[a.return] || 0) + 1;
});

Object.keys(count).forEach(function (k) {
    document.getElementById('id' + k).innerHTML = count[k];
});
<p>for the cases where return: 0 appears <span id="id0">0</span> times --- 1 Stop</p>
<p>for the cases where return: 1 appears <span id="id1">0</span> time --- Non-stop</p>

答案 2 :(得分:0)

快速ES 5解决方案:

var zeros = 0, ones = 0;

route.forEach(function(entry) {
    if(entry.return == 0) zeros++;
    else if(entry.return == 1) ones++;
});

alert("Zeros: " + zeros + " | Ones: " + ones);

答案 3 :(得分:0)

创建一个json对象。然后选择你想要的孩子。例如:

var jsonObject = data {
route: [
{
flyFrom: "CDG",
flyTo: "DUB",
return: 0,
},
{
flyFrom: "DUB",
flyTo: "SXF",
return: 0,
},
{
flyFrom: "SFX",
flyTo: "CDG",
return: 1,
}]
}

var zeroCount = 0;
var oneCount = 0;
for(var i = 0; i < jsonObject.route.length; i++){
var j = jsonObject.route[i].return;
if(j == 0) zeroCount++;
else oneCount++;
}

答案 4 :(得分:0)

此函数将返回一个包含两个键outboundinbound的对象,其中包含所需的消息,例如&#34;不间断&#34;,&#34; 1站&#34;等:

function countStops(route) { 
   const legs = route.reduce((result, r) => {
        const leg = r['return'] ? 'inbound' : 'outbound';
        result[leg]++;
        return result;
    }, { outbound: 0, inbound: 0 });

    const message = parts => {
        switch (parts) {
            case 1:
                return 'non-stop';
            case 2:
                return '1 stop';
            default:
                return `${parts - 1} stops`;
        }
    };

    return {
        outbound: message(legs.outbound),
        inbound: message(legs.inbound)
    };
}

请在此处查看fiddle