hw08_12_!ArrayOfObj.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <header>
  2. <h1>ArreyOfObject</h1>
  3. </header>
  4. <body>
  5. <script>
  6. const toHtmlTable = (arr) => {
  7. let str = "<table>";
  8. for (let arrEl of arr) {
  9. str += "<tr>";
  10. for (let val of arrEl) {
  11. str += `<td>${val}</td>`;
  12. }
  13. str += "</tr>";
  14. }
  15. str += "</table>";
  16. return str;
  17. }
  18. var persons = [
  19. { name: "Иван", age: 17 },
  20. { name: "Мария", age: 35 },
  21. { name: "Алексей", age: 73 },
  22. { name: "Яков", age: 12 },
  23. ]
  24. /*a b comp< asc res
  25. 1 2 true false false
  26. 2 1 false false true
  27. 1 2 true true true
  28. 2 1 false true false*/
  29. const sort = (arr, name, asc = true) =>
  30. arr.sort((a, b) => (a[name] < b[name]) == asc ? -1 : 1);
  31. sort(persons, "age"); //сортирует по возрасту по возрастанию
  32. document.write(toHtmlTable(persons.map(p => Object.entries(p))));
  33. sort(persons, "name", false); //сортирует по имени по убыванию
  34. document.write(toHtmlTable(persons.map(p => Object.entries(p))));
  35. </script>
  36. </body>