-1

This is the url from which i have to fetch data.I want the frequency of the postIds.How can i do this using the methods (map,filter or reduce).I've done it using a loop .Can it be done in a better way?.please help..

<!DOCTYPE html>
<html lang="en">
<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>

4
  • Note the answers given only iterate the array once whereas using filter() to create a new array to get it's length iterates the array once for every item in it Commented Jun 28, 2020 at 20:03
  • @-charlietfl thank you...i knew there must be a better way to do this..what i was doing was similar to using a nested loop.. Commented Jun 28, 2020 at 20:15
  • Right...plus each returned filter array takes up needless memory until it gets garbage collected Commented Jun 28, 2020 at 20:20
  • @charlietfl yeah ..first i thought of emptying the array with a=[] but i knew i had to post it as a question so i shouldn't optimize a wrong approach lol..and i used a predefined length as well which was also wrong..thank you once again Commented Jun 28, 2020 at 20:24

3 Answers 3

2

I hope this helps

let counterObj = {};

let cars = [
    { id: 1, name: 'Mercedes', year: '2015' },
    { id: 2, name: 'Mercedes', year: '2000' },
    { id: 3, name: 'BMW', year: '2010' },
    { id: 4, name: 'BMW', year: '2004' },
    { id: 5, name: 'Volvo', year: '2012' },
    { id: 6, name: 'Volvo', year: '2014' } 
];


for (let item of cars){
    counterObj[item.name] = 1 + (counterObj[item.name] || 0)
}

console.log(counterObj);

Sign up to request clarification or add additional context in comments.

1 Comment

I have to solve it with reduce,map or filter and nothing else.Thank you for answering but i want a solution that uses these methods only.
1

You can use reduce to generate a map of PostId with its frequency.

function mapFrequency(data) {
     return data.reduce((map, datum) => {
        if (map[datum.postId]) {
          map[datum.postId] += 1;
        } else {
          map[datum.postId] = 1 
        }
        return map;
        
     }, {})
}

This function will create an object with keys as postId and value as its frequency.

If you want to generate an array as in your sample, you can then do

 const frequencies = mapFrequency(data);
 const result = Object.keys(frequencies).map((id) => {
   return {
      PostId: id, 
      frequency: frequencies[id]
   }
  });

1 Comment

Thank You for your help : )
1

With reduce you can do something like this:

const na = data.reduce((acc, el) => {
  acc[el.postId] = acc[el.postId] ? acc[el.postId] + 1 : 1;
  return acc;
}, {});

Pretty much the same as @sonEtLumiere suggested, but with reduce

1 Comment

thank you..this is how i wanted ..I just wanted to know that can I use map on your answer to get the result in the form of {postId: postIdNumber,frequency: frequencyOfPostId}?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.