Advertisement
Grossos

map()

Nov 3rd, 2023 (edited)
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Storage
  2. // Write a function that takes a certain number of items and their quantity. If the same item appears more than once,
  3. // add the new amount to the existing one. In the end, print all the items and their amount without sorting them. The
  4. // input comes as an array of strings. Try using a Map().
  5.  
  6. function solve(arr) {
  7.  
  8.     let map = new Map();
  9.  
  10.     for (let string of arr) {
  11.         let tokens = string.split(' ');
  12.         let product = tokens[0];
  13.         let quantity = Number(tokens[1]);
  14.  
  15.         if(!map.has(product)) {
  16.             map.set(product, +quantity);
  17.         } else {
  18.             let currQuantity = map.get(product)
  19.             let newQuantity = currQuantity += quantity;
  20.             map.set(product, newQuantity);
  21.         }
  22.     }
  23.  
  24.     for (let kvp of map) {
  25.         console.log(`${kvp[0]} -> ${kvp[1]}`);
  26.     }
  27.  
  28. }
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement