Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Denislava91 avatar Denislava91 5 Точки

JS Advanced, Object and Classes Exercise, 08.Tickets

Здравейте,колеги,

 

Имам проблем със следната задача и ще съм много благодарна за малко помощ-

не мога да си изпечатам правилно масива от обекти на конзолата.

Благодаря предварително!

https://pastebin.com/sjqCM9WX 

 

 

1.Tickets

Write a program that manages a database of tickets. A ticket has a destination, a price and a status. Your program will receive two arguments - the first is an array of strings for ticket descriptions and the second is a string, representing a sorting criterion. The ticket descriptions have the following format:

<destinationName>|<price>|<status>

Store each ticket and at the end of execution return a sorted summary of all tickets, sorted by either destination, price or status, depending on the second parameter that your program received. Always sort in ascending order (default behavior for alphabetical sort). If two tickets compare the same, use order of appearance. See the examples for more information.

Input

Your program will receive two parameters - an array of strings and a single string.

Output

Return a sorted array of all the tickets that where registered.

Examples

Sample Input

Output Array

['Philadelphia|94.20|available',

 'New York City|95.99|available',

 'New York City|95.99|sold',

 'Boston|126.20|departed'],

'destination'

[ Ticket { destination: 'Boston',

    price: 126.20,

    status: 'departed' },

  Ticket { destination: 'New York City',

    price: 95.99,

    status: 'available' },

  Ticket { destination: 'New York City',

    price: 95.99,

    status: 'sold' },

  Ticket { destination: 'Philadelphia',

    price: 94.20,

    status: 'available' } ]

['Philadelphia|94.20|available',

 'New York City|95.99|available',

 'New York City|95.99|sold',

 'Boston|126.20|departed'],

'status'

[ Ticket { destination: 'Philadelphia',

    price: 94.20,

    status: 'available' },

  Ticket { destination: 'New York City',

    price: 95.99,

    status: 'available' },

  Ticket { destination: 'Boston',

    price: 126.20,

    status: 'departed' },

  Ticket { destination: 'New York City',

    price: 95.99,

    status: 'sold' } ]

Тагове:
0
JavaScript Advanced
krasizorbov avatar krasizorbov 548 Точки
Best Answer

без клас:

function solve(input, filterCriteria) {
 
  let tickets = [];
  input.forEach((line) => {
    [destination, price, status] = line.split("|");
    price = Number(price);
      tickets.push({ destination, price, status });
  });
  let sorted;
  if (filterCriteria === "destination") {
    sorted = tickets.sort((curr, next) =>
      curr.destination.localeCompare(next.destination)
    );
  } else if (filterCriteria === "price") {
    sorted = tickets.sort((curr, next) => curr.price - next.price);
  } else {
    sorted = tickets.sort((curr, next) =>
      curr.status.localeCompare(next.status)
    );
  }
  return sorted;
}

0
DaniyalAhmed avatar DaniyalAhmed 2 Точки

It was so good to see you acknowledging this topic, it really feels great. Thanks for sharing such a valuable information which is very hard to find normally. I have subscribed to your website and will be promoting it to my friends and other people as well. John Dutton Yellowstone Jacket

0
2
krasizorbov avatar krasizorbov 548 Точки

ето с някои добавки, може и без клас:

function solve(input, filterCriteria) {
  class Ticket {
    constructor(destination, price, status) {
      this.destination = destination;
      this.price = price;
      this.status = status;
    }
  }
  let tickets = [];
  input.forEach((line) => {
    [destination, price, status] = line.split("|");
    price = Number(price);
    tickets.push(new Ticket(destination, price, status));
  });
  let sorted;
  if (filterCriteria === "destination") {
    sorted = tickets.sort((curr, next) =>
      curr.destination.localeCompare(next.destination)
    );
  } else if (filterCriteria === "price") {
    sorted = tickets.sort((curr, next) => curr.price - next.price);
  } else {
    sorted = tickets.sort((curr, next) =>
      curr.status.localeCompare(next.status)
    );
  }
  return sorted;
}

 

0
03/10/2020 13:44:57
max00 avatar max00 1 Точки

https://codepen.io/maximilian-berovsky/pen/wvzQjNw

0
gbsho avatar gbsho 9 Точки

без клас, с по-малко редове:

function tickets(arr, str){
    let tickets = arr.map(e=>{
            let [destination,price,status] = e.split("|");
            price = Number(price);
            return {destination, price, status};
        }).sort((a,b)=>{
            if(str==="price"){
                return 0;
            }else{
                return a[str].localeCompare(b[str]);
            }
        });
    return tickets;
}

0
19/10/2022 12:01:12
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.