Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const getCitiesByPopulation = (obj, N) => {
- let citiesWithPopulation = obj.reduce ((acc, el) => {
- let counter = acc[el.address.city]?? 0
- return {
- ...acc,
- [el.address.city]: counter + 1
- }
- },[]) //връща обект с градове и общо население {Monroe: 2, Everett: 3 и т.н}
- // console.log(citiesWithPopulation)
- let indexRank = [];
- for (let key in citiesWithPopulation){
- indexRank.push(citiesWithPopulation[key])
- }
- indexRank = indexRank.sort((a,b) => b-a) //връща сортиран масив с бойките население : [3,3,3,2,2]
- let result = [];
- for (let i = 0; i<=N-1; i++){
- //взема първите N по ред числа от масива и прави обект от градовете които имат такова население.
- let population = indexRank[i]
- for(let key in citiesWithPopulation){
- if (population === citiesWithPopulation[key]){
- result.push({'name': key, 'population':citiesWithPopulation[key]})
- delete citiesWithPopulation[key]
- break;
- }
- }
- }
- return result;
- }
- console.log( getCitiesByPopulation(employees,3));
Advertisement
Add Comment
Please, Sign In to add comment