wealth list with Javascript array methods

 

Image for post

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().

eatures:

fetch random user api

create elements and appendChild to DOM

TML

first remenmber to link the css and js in html file

Image for post

aside is all the button with event added later in js

the main stores the data list

SS

Image for post

imported the font from Google fonts if you want

make everything in the center

Image for post

with the line separating the aside and main

Image for post

the title aligns at the other side with space-between

the h3 and .person will be appended in js

S

Image for post

get the DOM and set an array to store the new data

Image for post

the five events listeners represent five events buttons in the aside

add a new user:

Image for post

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

Image for post

how to show the fetched data in the browser? updateDOM() it is

Image for post

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():

Image for post

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():

Image for post

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():

Image for post

filter the number larger than a million and update DOM

calculate the total wealth with reduce():

Image for post

accumulate each array number and format the number to currency string

Image for post

Popular posts from this blog

Fancyapps — easily build overlay windows with carousel

Thoughts about Progressive Web App

Meet Mantine: A TS-Based Open-Source React Components Library