1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <header>
- <h1>Table</h1>
- </header>
- <body>
- <script>
- var arr = [
- {
- "Name": "chevrolet chevelle malibu",
- "Cylinders": 8,
- "Displacement": 307,
- "Horsepower": 130,
- "Weight_in_lbs": 3504,
- "Origin": "USA"
- },
- {
- "Name": "buick skylark 320",
- "Miles_per_Gallon": 15,
- "Cylinders": 8,
- "Displacement": 350,
- "Horsepower": 165,
- "Weight_in_lbs": 3693,
- "Acceleration": 11.5,
- "Year": "1970-01-01",
- },
- {
- "Miles_per_Gallon": 18,
- "Cylinders": 8,
- "Displacement": 318,
- "Horsepower": 150,
- "Weight_in_lbs": 3436,
- "Year": "1970-01-01",
- "Origin": "USA"
- },
- {
- "Name": "amc rebel sst",
- "Miles_per_Gallon": 16,
- "Cylinders": 8,
- "Displacement": 304,
- "Horsepower": 150,
- "Year": "1970-01-01",
- "Origin": "USA"
- },
- ];
- const sort = (arr, name, asc = true) =>
- arr.sort((a, b) => ((a[name] || "") < (b[name] || "")) == asc ? -1 : 1); //предусматриваем пустой ключ для конкретного объекта
- const copySorter = (arr, sortName, asc = true) => {
- //const copy = {...person}
- sortedArr = sort(
- [...arr],
- sortName,
- asc);
- names = Object
- .entries(
- sortedArr.reduce(
- (prev, next) => {
- return { ...prev, ...next };
- }
- ))
- .map(entry => entry[0]);
- str = "<table>";
- str += "<tr>" +
- names
- .map(name => `<td>${name}</td>`)
- .join('') +
- "</tr>";
- str +=
- sortedArr
- .map(obj =>
- `<tr>${names
- .map(name => `<td>${obj[name] || "-"}</td>`)
- .join('')
- }</tr>`)
- .join('');
- str += "</table>";
- return str;
- }
- document.write(copySorter(arr, "Displacement", true));
- </script>
- </body>
|