Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(arr){
- let townList=[];
- for(let current of arr){
- let listOfnames=townList.map(x=>x.name);
- let exist=listOfnames.includes(current.town);
- if(exist){
- let townNeeded=townList.find(x=>x.name===current.town);
- let newObjForTown={
- "model":current.model,
- "regNumber":current.regNumber,
- };
- townNeeded.car.push(newObjForTown);
- townNeeded.totalPrice+=Number(current.price);
- townNeeded.totalCar+=1;
- }
- else{
- let newTown={
- 'car':[],
- 'totalPrice':0,
- 'totalCar':0,
- 'name':current.town
- };
- let newCar={
- 'model':current.model,
- 'regNumber':current.regNumber,
- 'price':Number(current.price)
- }
- newTown.car.push(newCar);
- newTown.totalPrice+=Number(current.price);
- newTown.totalCar+=1;
- townList.push(newTown);
- }
- }
- let sortedTowns =townList.sort((a,b)=>b.totalPrice - a.totalPrice || b.car.length - a.car.length || a.name.localeCompare(b.name));
- let mostUsedCar=GetMostUsedCar(sortedTowns[0]);
- function GetMostUsedCar(town){
- let array=town.car.map(x=>x.model);
- var counts = {};
- var compare = 0;
- var mostFrequent;
- for(var i = 0, len = array.length; i < len; i++){
- var word = array[i];
- if(counts[word] === undefined){
- counts[word] = 1;
- }else{
- counts[word] = counts[word] + 1;
- }
- if(counts[word] > compare){
- compare = counts[word];
- mostFrequent = array[i];
- }
- }
- return mostFrequent;
- }
- let firstTown=sortedTowns[0];
- console.log(`${firstTown.name} is most profitable - ${firstTown.totalPrice} BGN`);
- console.log(`Most driven model: ${mostUsedCar}`);
- let printTowns=sortedTowns
- .sort((a,b)=>a.name.localeCompare(b.name))
- .filter(x=>x.car.some(c=>c.model===mostUsedCar))
- .filter(x=>x)
- .map(x=>{
- return {
- "townName":x.name,
- "plates":x.car.filter(x=>x.model===mostUsedCar)
- .map(x=>x.regNumber)
- .sort((a,b)=>a.localeCompare(b))
- .join(', ')
- }
- });
- printTowns.forEach(x=>console.log(`${x.townName}: ${x.plates}`));
- }
Advertisement
Add Comment
Please, Sign In to add comment