Advertisement
dimipan80

Exams - Sort Table

Nov 17th, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* You are given a HTML table with 3 columns: product, price and votes. Write a JavaScript function to sort
  2. the table rows by price (as number, increasingly). The input is passed to the first JavaScript function
  3. found in your code as array of strings in the format of the examples below. The HTML table will always have
  4. a header row and 3 columns: product, price and votes. No whitespace will be found between the tags
  5. and between the tags and the tags values. When several rows hold equal prices, use the product name
  6. as second sort criteria (sort by product name alphabetically).*/
  7.  
  8. "use strict";
  9.  
  10. function sortTableRowsByPrice(arr) {
  11.     var products = [];
  12.     var pattern = /<tr><td>([^<]+)<\/td><td>([^<]+)<\/td><td>[^<]+<\/td><\/tr>/g;
  13.     for (var i = 2; i + 1 < args.length; i += 1) {
  14.         var rowObj = {};
  15.         var matcher;
  16.         while (matcher = pattern.exec(args[i])) {
  17.             rowObj['fullRow'] = matcher[0];
  18.             rowObj['productName'] = matcher[1].trim();
  19.             rowObj['price'] = Number(matcher[2]);
  20.         }
  21.         products.push(rowObj);
  22.     }
  23.  
  24.     products.sort(function(prod1, prod2) {
  25.         return (prod1.price != prod2.price) ? (prod1.price - prod2.price) :
  26.         prod1.productName > prod2.productName;
  27.     });
  28.  
  29.     console.log(args[0]);
  30.     console.log(args[1]);
  31.     for (i = 0; i < products.length; i += 1) {
  32.         console.log(products[i].fullRow);
  33.     }
  34.     console.log(args[args.length - 1]);
  35. }
  36.  
  37. console.log(sortTableRowsByPrice(['<table>',
  38.     '<tr><th>Product</th><th>Price</th><th>Votes</th></tr>',
  39.     '<tr><td>Vodka Finlandia 1 l</td><td>19.35</td><td>+12</td></tr>',
  40.     '<tr><td>Ariana Radler 0.5 l</td><td>1.19</td><td>+33</td></tr>',
  41.     '<tr><td>Laptop HP 250 G2</td><td>629</td><td>+1</td></tr>',
  42.     '<tr><td>Kamenitza Grapefruit 1 l</td><td>1.85</td><td>+7</td></tr>',
  43.     '<tr><td>Cofee Davidoff 250 gr.</td><td>11.99</td><td>+11</td></tr>',
  44.     '</table>']));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement