elena1234

For loop through objects - JavaScript

Aug 31st, 2021 (edited)
1,606
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(array) {
  2.     let cars = {};
  3.     array.forEach(row => {
  4.         let [brand, model, numberOfCars] = row.split(' | ');
  5.         numberOfCars = Number(numberOfCars);
  6.         if (!cars[brand]) {
  7.             cars[brand] = [];
  8.             cars[brand].push({ model, numberOfCars });
  9.         } else if (cars[brand] && !cars[brand].some(car => car.model === model)) {
  10.             cars[brand].push({ model, numberOfCars });
  11.         } else {
  12.             let findedCar = cars[brand].find(car => car.model === model);
  13.             findedCar.numberOfCars += Number(numberOfCars);
  14.         }
  15.     });
  16.  
  17.     for (const [currentBrand, carsCurrentBrand] of Object.entries(cars)) {
  18.         console.log(currentBrand);
  19.         for (const currentCar of Object.values(carsCurrentBrand)) {
  20.             console.log(`###${currentCar.model} -> ${currentCar.numberOfCars}`);
  21.         }
  22.     }
  23. }
  24.  
  25. solve(['Audi | Q7 | 1000',
  26. 'Audi | Q6 | 100',
  27. 'BMW | X5 | 1000',
  28. 'BMW | X6 | 100',
  29. 'Citroen | C4 | 123',
  30. 'Volga | GAZ-24 | 1000000',
  31. 'Lada | Niva | 1000000',
  32. 'Lada | Jigula | 1000000',
  33. 'Citroen | C4 | 22',
  34. 'Citroen | C5 | 10'])
Add Comment
Please, Sign In to add comment