wealth list with Javascript array methods
This demo is learned from Brad Traversy’s course.
Demo Github
When mentioning of Array, there always is a list coming up in my mind. The first thing of Javascript is manipulating DOM to achieve the goal.
This demo concludes the arrray methods:sort(),forEach(),map() and filter().
Features:
fetch random user api
create elements and appendChild to DOM
HTML
first remenmber to link the css and js in html file
aside is all the button with event added later in js
the main stores the data list
CSS
imported the font from Google fonts if you want
make everything in the center
with the line separating the aside and main
the title aligns at the other side with space-between
the h3 and .person will be appended in js
JS
get the DOM and set an array to store the new data
the five events listeners represent five events buttons in the aside
add a new user:
To fetch random user names, it’s easy to use a random user generator API
If you come to Access-control-allow-origin error, try to understand the answer in the article to handle it. (explained why I use this way to fix it here)
async and await to fetch the JSON data and store the data includes name and money into an object and add data to DOM
how to show the fetched data in the browser? updateDOM() it is
every time run the function, clear the main content
the default data is the stored object
loop the data and append to the created Div
Double wealth event with map():
map the data and multiply by 2 to money in the array
…user: spread operator
at last, update the DOM
sorted the list from max to min with sort():
from max to min: (a,b)=>b.money-a.money
from min to max:(a,b)=>a.money-b.money
pick up the millionaires with filter():
filter the number larger than a million and update DOM
calculate the total wealth with reduce():
accumulate each array number and format the number to currency string