I have to write a program that takes 2 parallel arrays, one with the title of five books and then another with the publication dates for the books. All of the examples I have seen using a selection sort are sorting integers for smallest to largest. Is there a way to change the string dates into a numeric value later on in the program. I am supposed to display the initial list first and then again after it has been ordered.
Here is my code for the arrays.
function getBooks() {
var bookTitles = new Array();
bookTitles[0] = " To Kill a Mockingbird ";
bookTitles[1] = " Jaws ";
bookTitles[2] = " Don Quixote ";
bookTitles[3] = " Moby-Dick ";
bookTitles[4] = " Northern Lights ";
var bookDates = new Array();
bookDates[0] = " July 11, 1960 ";
bookDates[1] = " Febuary 1, 1974 ";
bookDates[2] = " July 11, 1615 ";
bookDates[3] = " October 18, 1851 ";
bookDates[4] = " November 12, 1995 ";
document.getElementById("book_output").innerHTML = bookTitles "</br> " bookDates;
}
HTML.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CIS 223 Lab Assignment #9</title>
</head>
<body onl oad="getBooks()">
<script type="text/javascript" src="Drackley_Lab9_2.js" charset="utf-8"></script>
<h3 id="book_output"></h3>
</body>
</html>
CodePudding user response:
One way to solve this is to combine the two arrays into an array of objects with a timestamp (from converting the date string into a Date object) and then sort that array based on the timestamps. You can then use the sorted array to generate your output HTML:
var bookTitles = new Array();
bookTitles[0] = " To Kill a Mockingbird ";
bookTitles[1] = " Jaws ";
bookTitles[2] = " Don Quixote ";
bookTitles[3] = " Moby-Dick ";
bookTitles[4] = " Northern Lights ";
var bookDates = new Array();
bookDates[0] = " July 11, 1960 ";
bookDates[1] = " February 1, 1974 ";
bookDates[2] = " July 11, 1615 ";
bookDates[3] = " October 18, 1851 ";
bookDates[4] = " November 12, 1995 ";
books = bookTitles
.map((e, i) => ({
title: e,
date: bookDates[i],
ts: new Date(bookDates[i]).getTime()
}))
.sort((a, b) => a.ts - b.ts)
result = document.getElementById('result')
result.innerHTML = '<table>'
books.map(o => '<tr><td>' o.title '</td><td>' o.date '</td></tr>').join('')
'</table>'
<div id="result"></div>
CodePudding user response:
You can convert your dates into integers using Date.parse()
.
console.log(Date.parse(" July 11, 1960 "));
console.log(Date.parse(" Febuary 1, 1974 "));
console.log(Date.parse(" November 12, 1995 "));