Loading...
inaivanova1990 avatar inaivanova1990 33 Точки

6. Make a Dictionary from Fundamentals with JS

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

Много ми се ще да направя това решение по-декларативно с помощта на reduce, map, filter и да избегна , доколкото е възможно for - циклите.

Ще се радвам, ако някой редактира това решение или просто ми даде насоки!

 

Код: https://pastebin.com/zGV8g91a

 

Задача: You will receive an array with strings in the form of JSON's.

You have to parse these strings and combine them into one object. Every string from the array will hold terms and a description. If you receive the same term twice, replace it with the new definition.

Print every term and definition in that dictionary on new line in format:

`Term: ${term} => Definition: ${definition}`

Don't forget to sort the dictionary alphabetically by the terms as in real dictionaries.

Examples

Input

Output

[

'{"Coffee":"A hot drink made from the roasted and ground seeds (coffee beans) of a tropical shrub."}',

'{"Bus":"A large motor vehicle carrying passengers by road, typically one serving the public on a fixed route and for a fare."}',

'{"Boiler":"A fuel-burning apparatus or container for heating water."}',

'{"Tape":"A narrow strip of material, typically used to hold or fasten something."}',

'{"Microphone":"An instrument for converting sound waves into electrical energy variations which may then be amplified, transmitted, or recorded."}'

]

Term: Boiler => Definition: A fuel-burning apparatus or container for heating water.

Term: Bus => Definition: A large motor vehicle carrying passengers by road, typically one serving the public on a fixed route and for a fare.

Term: Coffee => Definition: A hot drink made from the roasted and ground seeds (coffee beans) of a tropical shrub.

Term: Microphone => Definition: An instrument for converting sound waves into electrical energy variations which may then be amplified, transmitted, or recorded.

Term: Tape => Definition: A narrow strip of material, typically used to hold or fasten something.

[

'{"Cup":"A small bowl-shaped container for drinking from, typically having a handle"}',

'{"Cake":"An item of soft sweet food made from a mixture of flour, fat, eggs, sugar, and other ingredients, baked and sometimes iced or decorated."} ',

'{"Watermelon":"The large fruit of a plant of the gourd family, with smooth green skin, red pulp, and watery juice."} ',

'{"Music":"Vocal or instrumental sounds (or both) combined in such a way as to produce beauty of form, harmony, and expression of emotion."} ',

'{"Art":"The expression or application of human creative skill and imagination, typically in a visual form such as painting or sculpture, producing works to be appreciated primarily for their beauty or emotional power."} '

]

Term: Art => Definition: The expression or application of human creative skill and imagination, typically in a visual form such as painting or sculpture, producing works to be appreciated primarily for their beauty or emotional power.

Term: Cake => Definition: An item of soft sweet food made from a mixture of flour, fat, eggs, sugar, and other ingredients, baked and sometimes iced or decorated.

Term: Cup => Definition: A small bowl-shaped container for drinking from, typically having a handle

Term: Music => Definition: Vocal or instrumental sounds (or both) combined in such a way as to produce beauty of form, harmony, and expression of emotion.

Term: Watermelon => Definition: The large fruit of a plant of the gourd family, with smooth green skin, red pulp, and watery juice.

Тагове:
1
Fundamentals Module 20/05/2022 19:45:41
Axiomatik avatar Axiomatik 2422 Точки
Best Answer

;-)

function solve(arr) {
    // let copy = [];
    // let obj = {};

    // for (let element of arr) {
    //     let converted = JSON.parse(element);
    //     if (typeof converted === 'object') {
    //         for (let key in converted) {
    //             obj[key] = converted[key];
    //         }
    //     }

    // }
    // for (let key in obj) {
    //     copy.push(`Term: ${key} => Definition: ${obj[key]}`)

    // }

    let array = input.reduce((acc, curr, i) => {
        let term = Object.keys(JSON.parse(curr))[0];
        let text = Object.values(JSON.parse(curr))[0];
        acc.push({ [term]: text });

        return acc;
    }, []);

    let copy = array
        .sort((a, b) => Object.keys(a)[0].localeCompare(Object.keys(b)[0]))
        .map((el) => {
            return `Term: ${Object.keys(el)[0]} => ${Object.values(el)[0]}`;
        })
        .join('\n');

    return copy;
}

 

0
20/05/2022 20:50:23
inaivanova1990 avatar inaivanova1990 33 Точки

Супер, благодаря!:)

1
inaivanova1990 avatar inaivanova1990 33 Точки

Още един въпрос - как да получим масив, в който term  да не се повтаря и да получим последната дефиниция на съответния term??

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