Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a HTML table with 3 columns: product, price and votes. Write a JavaScript function to sort
- the table rows by price (as number, increasingly). The input is passed to the first JavaScript function
- found in your code as array of strings in the format of the examples below. The HTML table will always have
- a header row and 3 columns: product, price and votes. No whitespace will be found between the tags
- and between the tags and the tags values. When several rows hold equal prices, use the product name
- as second sort criteria (sort by product name alphabetically).*/
- "use strict";
- function sortTableRowsByPrice(arr) {
- var products = [];
- var pattern = /<tr><td>([^<]+)<\/td><td>([^<]+)<\/td><td>[^<]+<\/td><\/tr>/g;
- for (var i = 2; i + 1 < args.length; i += 1) {
- var rowObj = {};
- var matcher;
- while (matcher = pattern.exec(args[i])) {
- rowObj['fullRow'] = matcher[0];
- rowObj['productName'] = matcher[1].trim();
- rowObj['price'] = Number(matcher[2]);
- }
- products.push(rowObj);
- }
- products.sort(function(prod1, prod2) {
- return (prod1.price != prod2.price) ? (prod1.price - prod2.price) :
- prod1.productName > prod2.productName;
- });
- console.log(args[0]);
- console.log(args[1]);
- for (i = 0; i < products.length; i += 1) {
- console.log(products[i].fullRow);
- }
- console.log(args[args.length - 1]);
- }
- console.log(sortTableRowsByPrice(['<table>',
- '<tr><th>Product</th><th>Price</th><th>Votes</th></tr>',
- '<tr><td>Vodka Finlandia 1 l</td><td>19.35</td><td>+12</td></tr>',
- '<tr><td>Ariana Radler 0.5 l</td><td>1.19</td><td>+33</td></tr>',
- '<tr><td>Laptop HP 250 G2</td><td>629</td><td>+1</td></tr>',
- '<tr><td>Kamenitza Grapefruit 1 l</td><td>1.85</td><td>+7</td></tr>',
- '<tr><td>Cofee Davidoff 250 gr.</td><td>11.99</td><td>+11</td></tr>',
- '</table>']));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement