elena1234

For loop through objects - print JavaScript

Aug 31st, 2021 (edited)
1,156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(array) {
  2.     let products = [];
  3.     array.forEach(line => {
  4.         let [productName, productPrice] = line.split(' : ');
  5.         productPrice = Number(productPrice);
  6.         let product = {
  7.             name: productName,
  8.             price: productPrice,
  9.         }
  10.  
  11.         products.push(product);
  12.     });
  13.  
  14.     products.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
  15.  
  16.     let currentLetter = '';
  17.     for (const product of products) {
  18.         if (product.name.charAt(0).toUpperCase() === currentLetter) {
  19.             console.log(`  ${product.name}: ${product.price}`)
  20.         } else {
  21.             currentLetter = product.name.charAt(0).toUpperCase();
  22.             console.log(currentLetter);
  23.             console.log(`  ${product.name}: ${product.price}`)
  24.         }
  25.     }
  26. }
  27.  
  28. solve(['Appricot : 20.4',
  29. 'Fridge : 1500',
  30. 'TV : 1499',
  31. 'Deodorant : 10',
  32. 'Boiler : 300',
  33. 'Apple : 1.25',
  34. 'Anti-Bug Spray : 15',
  35. 'T-Shirt : 10'])
Add Comment
Please, Sign In to add comment