如何使用javascript(过滤器)来计算对象值的频率?

这是我必须从中获取数据的url。我想要 postIds 的频率。我如何使用方法(map、filter 或 reduce)来做到这一点。我已经使用循环完成了。可以在更好的方法?请帮助..

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

    <script>

  fetch('http://jsonplaceholder.typicode.com/comments')

  .then(

    function(response) {

      if (response.status !== 200) {

        console.log('Looks like there was a problem. Status Code: ' +

          response.status);

        return;

      }

      response.json().then(function(data) 

      {

          var na=[];

          for(var i=1;i<=100;i++)

          {

            var a= data.filter(ab=> {

          return ab.postId==i;});

         // console.log(a); 

          na.push({PostId:i,frequency:a.length});

          }

          console.log(na);

      }

  )})

  .catch(function(err) {

    console.log('Fetch Error :-S', err);

  });

    </script>

</body>

</html>



UYOU
浏览 134回答 3
3回答

HUX布斯

我希望这有帮助let counterObj = {};let cars = [&nbsp; &nbsp; { id: 1, name: 'Mercedes', year: '2015' },&nbsp; &nbsp; { id: 2, name: 'Mercedes', year: '2000' },&nbsp; &nbsp; { id: 3, name: 'BMW', year: '2010' },&nbsp; &nbsp; { id: 4, name: 'BMW', year: '2004' },&nbsp; &nbsp; { id: 5, name: 'Volvo', year: '2012' },&nbsp; &nbsp; { id: 6, name: 'Volvo', year: '2014' }&nbsp;];for (let item of cars){&nbsp; &nbsp; counterObj[item.name] = 1 + (counterObj[item.name] || 0)}console.log(counterObj);

呼唤远方

您可以使用其频率reduce生成地图。PostIdfunction mapFrequency(data) {&nbsp; &nbsp; &nbsp;return data.reduce((map, datum) => {&nbsp; &nbsp; &nbsp; &nbsp; if (map[datum.postId]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map[datum.postId] += 1;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map[datum.postId] = 1&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return map;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;}, {})}此函数将创建一个对象,其键为 as postId,值为其频率。如果你想在你的样本中生成一个数组,你可以这样做&nbsp;const frequencies = mapFrequency(data);&nbsp;const result = Object.keys(frequencies).map((id) => {&nbsp; &nbsp;return {&nbsp; &nbsp; &nbsp; PostId: id,&nbsp;&nbsp; &nbsp; &nbsp; frequency: frequencies[id]&nbsp; &nbsp;}&nbsp; });

慕沐林林

使用 reduce,您可以执行以下操作:const na = data.reduce((acc, el) => {&nbsp; acc[el.postId] = acc[el.postId] ? acc[el.postId] + 1 : 1;&nbsp; return acc;}, {});与@sonEtLumiere 建议的几乎相同,但与reduce
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript