I'm new to Javascript and doing some exercises I found online. Since I want to really understand how things work and why some approaches are better than others, I would appreciate some feedback why my approaches are bad (or good).
I have an XML and process it with the SAX parser to get "trending keywords". As an overall result, my function should return the 5 most popular ones. The result of my parsing itself is an array with 20 objects in the format
[{
attributes: {}
//children is just one big entry, separated by ';'
children: ["Comey, James B;Federal Bureau of Investigation;Trump, Donald J;United States Politics and Government"]
IsSelfClosing: false,
name: 'ADX_KEYWORDS',
parent: null,
__proto__: {}
}]
Now my idea was, to pull out all those children
values and store it in a new array
let flattenArr = keywords.reduce( (acc, cur) => acc.concat(cur.children), []);
As result I get an array (also length 20) in the format
[["Comey, James B;Federal Bureau of Investigation;Trump, Donald J;United States Politics and Government"],
["Trump, Donald J;Comey, James B;Federal Bureau of Investigation;United States Politics and Government"]]
To process the single values, I split the array
let mapArr = flattenArr
.map( arr => arr.split(';') )
.reduce( (acc, cur) => acc.concat(cur), [] );
and as a result, the new array of length 115 contains every single keyword separated. And here is the point where I don't know how to proceed. I tried the example from MDN(Array.Reduce) but didn't really know if (and how) I would be able to process these object.
//Result from MDN example, {value: quantity}
{ 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
So I had the idea of creating an object for every keyword, with a property for its quantity
{
key: keyword,
count: n
}
and tried to accomplish this with
let countKeywords = mapArrreduce( (allKeywords, keyword) => {
if (allKeywords[0] != null && keyword in allKeywords[keyword]) {
allKeywords[keyword].count++
} else {
allKeywords.push({
keyword: keyword,
count: 1
})
}
return allKeywords;
}, []);
but my code doesn't work, and even after two days I still struggle to make it work, which made me post this question (which is kinda new for me, since I always found my answers on stackoverflow and therefore never had to ask a question myself)
via Tobias
No comments:
Post a Comment