const users = [
{ id: 5, name: "user 5" },
{ id: 3, name: "user 3" },
{ id: 1, name: "user 1" },
{ id: 2, name: "user 2" },
{ id: 4, name: "user 4" },
{ id: 8, name: "user 8" },
{ id: 7, name: "user 7" }
];
const getUsers = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(users);
}, 300);
});
};
export { users, getUsers };
date.js
import "./styles.css";
import { users, getUsers } from "./data.js";
document.getElementById("app").innerHTML = `
<ul>
<li>Sort <b>users</b> array and display list of user names
inside div with class <b>sorted-array</b> instead placeholder</li>
<li>Find user with id equals to 4 and display
its name inside div with <b>data-user</b> attribute
equal to <b>4</b> instead placeholder</li>
<li>By using of function <b>getUsers</b> Load list of user
names inside div with id <b>users-from-promise</b> instead placeholder</li>
</ul>
<h2>Sorted users</h2>
<div class="sorted-array">
<i>placeholder</i>
</div>
<h2>User with id 4</h2>
<div data-user="4">
<i>placeholder</i>
</div>
<h2>Users from promise</h2>
<div id="users-from-promise">
<i>placeholder</i>
</div>
`;
index.js
body {
font-family: sans-serif;
}
styles.css
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="src/index.js">
</script>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<style>
li,
div {
width: 10em;
font: 400 0.95em system-ui;
padding: 0.05em 0.5em;
}
li span {
float: right;
font: 700 0.7em system-ui;
}
.highlighted {
background-color: lime;
}
</style>
<body onload="init()">
<script>
const mydiv = document.createElement('div');
mydiv.id = 'mydiv';
document.body.appendChild(mydiv);
const users = [
{ id: 5, name: "user 5" },
{ id: 3, name: "user 3" },
{ id: 1, name: "user 1" },
{ id: 2, name: "user 2" },
{ id: 4, name: "user 4" },
{ id: 8, name: "user 8" },
{ id: 7, name: "user 7" }
];
function init() {
displaySortedUserList();
findUserIdEquals(4);
}
function displaySortedUserList() {
const sorted_names = users.sort((a, b) => {
const af = a.name.toLowerCase(),
bf = b.name.toLowerCase(),
as = a.name.toLowerCase(),
bs = b.name.toLowerCase();
if(af == bf)
return (as < bs) ? -1 : (as > bs) ? 1 : 0;
else
return (af < bf) ? -1 : 1;
});
const list_names = sorted_names.map((row)=>(
`<li id="${row.id}">${row.name}<span>[id - ${row.id}]</span></li>`));
mydiv.innerHTML = `<ol>${list_names.join('')}</ol>`;
mydiv.classList.add('sorted-array');
}
function findUserIdEquals(id) {
const list_names = document.querySelectorAll('.sorted-array li');
for (const row of list_names)
if (row.id == id) {
row.classList.add('highlighted');
mydiv.innerHTML += `<div data-user="${id}">${row.textContent}</div>`;
}
}
</script>
</body>
</html>
troche zmienilem i chybo oto im chodzi