Reputation: 204
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>
Upvotes: -1
Views: 398
Reputation: 4562
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);
Upvotes: 2
Reputation: 1538
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]
}
});
Upvotes: 1
Reputation: 55
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
Upvotes: 1