I'm trying to use the map and filter example at:
var data = [
{
"pmid": 12637528,
"citation_count": 75
},
{
"pmid": 12732634,
"citation_count": 49
},
{
"pmid": 15118089,
"citation_count": 88
}
]
I am using
let iIndex = data.map(d => d.citation_count).filter( d.citation_count >=50);
and
let iIndex = data.map(d => d.citation_count).filter( data.citation_count >=50);
but I get the following error: "err = ReferenceError: d is not defined at eval" or with data.citation err = TypeError: false is not a function at Array.filter
If I take the .filter off it works fine, and I get an array of just the citation count. Can someone help with the correct syntax for the filter portion? I have searched stackOverflow but there are a lot of answers that are about 10 years old and I'm not sure what the most current direction has gone. I have even seen a mention of flatMap. Thanks for the help
It's unnecessary to have d.citation_count in filter:
let iIndex = data.map(d => d.citation_count).filter( d => d >=50);
The reason your code is failing is because filter expects a function that returns a boolean - you have provided it with an expression.
A simple fix to your code would be to wrap your expression in an anonymous function:
const result = data.map(item => item.citation_count).filter(count => count >= 50)
You could also just use reduce, which combines the effect of both the filter and map functions, making the code more efficient:
const data = [
{ pmid: 12637528, citation_count: 75 },
{ pmid: 12732634, citation_count: 49 },
{ pmid: 15118089, citation_count: 88 },
]
const result = data.reduce((result, { citation_count }) => {
if (citation_count >= 50) {
result.push(citation_count)
}
return result
}, [])
console.log(result)