hw08_13_!Table.html 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <header>
  2. <h1>Table</h1>
  3. </header>
  4. <body>
  5. <script>
  6. var arr = [
  7. {
  8. "Name": "chevrolet chevelle malibu",
  9. "Cylinders": 8,
  10. "Displacement": 307,
  11. "Horsepower": 130,
  12. "Weight_in_lbs": 3504,
  13. "Origin": "USA"
  14. },
  15. {
  16. "Name": "buick skylark 320",
  17. "Miles_per_Gallon": 15,
  18. "Cylinders": 8,
  19. "Displacement": 350,
  20. "Horsepower": 165,
  21. "Weight_in_lbs": 3693,
  22. "Acceleration": 11.5,
  23. "Year": "1970-01-01",
  24. },
  25. {
  26. "Miles_per_Gallon": 18,
  27. "Cylinders": 8,
  28. "Displacement": 318,
  29. "Horsepower": 150,
  30. "Weight_in_lbs": 3436,
  31. "Year": "1970-01-01",
  32. "Origin": "USA"
  33. },
  34. {
  35. "Name": "amc rebel sst",
  36. "Miles_per_Gallon": 16,
  37. "Cylinders": 8,
  38. "Displacement": 304,
  39. "Horsepower": 150,
  40. "Year": "1970-01-01",
  41. "Origin": "USA"
  42. },
  43. ];
  44. const sort = (arr, name, asc = true) =>
  45. arr.sort((a, b) => ((a[name] || "") < (b[name] || "")) == asc ? -1 : 1); //предусматриваем пустой ключ для конкретного объекта
  46. const copySorter = (arr, sortName, asc = true) => {
  47. //const copy = {...person}
  48. sortedArr = sort(
  49. [...arr],
  50. sortName,
  51. asc);
  52. names = Object
  53. .entries(
  54. sortedArr.reduce(
  55. (prev, next) => {
  56. return { ...prev, ...next };
  57. }
  58. ))
  59. .map(entry => entry[0]);
  60. str = "<table>";
  61. str += "<tr>" +
  62. names
  63. .map(name => `<td>${name}</td>`)
  64. .join('') +
  65. "</tr>";
  66. str +=
  67. sortedArr
  68. .map(obj =>
  69. `<tr>${names
  70. .map(name => `<td>${obj[name] || "-"}</td>`)
  71. .join('')
  72. }</tr>`)
  73. .join('');
  74. str += "</table>";
  75. return str;
  76. }
  77. document.write(copySorter(arr, "Displacement", true));
  78. </script>
  79. </body>