Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(input) {
- const products = [];
- const cities = [];
- for (const info of input) {
- let [town, product, price] = info.split(' | ');
- price = Number(price);
- if (!products.includes(product)) products.push(product);
- const city = cities.filter(x => x.town == town)
- if (city.length == 0) {
- cities.push({town:town, [product]: price});
- } else if (!Object.keys(city[0]).includes(product)) {
- city[0][product] = price;
- } else {
- city[0][product] = price;
- }
- }
- for (const product of products) {
- let lowersPriceTown = cities.filter(x => Object.keys(x).includes(product)).sort((a, b) => a[product] - b[product]);
- (checkSamePrice(lowersPriceTown, product)) ? lowersPriceTown = lowersPriceTown.sort((a, b) => cities.indexOf(a) - cities.indexOf(b))[0]
- : lowersPriceTown = lowersPriceTown[0];
- console.log(`${product} -> ${lowersPriceTown[product]} (${lowersPriceTown.town})`);
- }
- function checkSamePrice (arr, product) {
- for (let i = 0; i < arr.length - 1; i++) {
- if (arr[i][product] == arr[i + 1][product]) return true;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement