momo3141

Task 8

Jan 23rd, 2023
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const getCitiesByPopulation = (obj, N) => {
  2.     let citiesWithPopulation = obj.reduce ((acc, el) => {
  3.  
  4.         let counter = acc[el.address.city]?? 0
  5.  
  6.         return {
  7.             ...acc,
  8.             [el.address.city]: counter + 1
  9.         }
  10.  
  11.     },[]) //връща обект с градове и общо население {Monroe: 2, Everett: 3 и т.н}
  12.  
  13.     // console.log(citiesWithPopulation)
  14.  
  15.     let indexRank = [];
  16.     for (let key in citiesWithPopulation){
  17.         indexRank.push(citiesWithPopulation[key])
  18.     }
  19.  
  20.    indexRank = indexRank.sort((a,b) => b-a) //връща сортиран масив с бойките население : [3,3,3,2,2]
  21.  
  22.    let result = [];
  23.  
  24.    for (let i = 0; i<=N-1; i++){
  25.     //взема първите N по ред числа от масива и прави обект от градовете които имат такова население.
  26.     let population = indexRank[i]
  27.     for(let key in citiesWithPopulation){
  28.         if (population === citiesWithPopulation[key]){
  29.             result.push({'name': key, 'population':citiesWithPopulation[key]})
  30.             delete citiesWithPopulation[key]
  31.             break;
  32.         }
  33.     }
  34.    
  35.    }
  36.  
  37.  
  38.     return result;
  39. }
  40.  
  41. console.log( getCitiesByPopulation(employees,3));
Advertisement
Add Comment
Please, Sign In to add comment