Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Array methods#155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
otmon76 merged 1 commit intojavascript-tutorial:masterfromotmon76:1.5.5
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
functioncamelize(str) {
returnstr
.split('-') //splits 'my-long-word' into array ['my', 'long', 'word']
functioncamelizace(řetězec) {
returnřetězec
.split('-') //rozdělí 'mé-dlouhé-slovo' na pole ['', 'dlouhé', 'slovo']
.map(
//capitalizes first letters of all array items except the first one
//converts ['my', 'long', 'word']into ['my', 'Long', 'Word']
(word, index) => index == 0 ?word :word[0].toUpperCase() +word.slice(1)
//převede první písmena všech prvků pole kromě prvního na velká
//převede ['', 'dlouhé', 'slovo']na ['', 'Dlouhé', 'Slovo']
(slovo, index) => index == 0 ?slovo :slovo[0].toUpperCase() +slovo.slice(1)
)
.join(''); //joins ['my', 'Long', 'Word']into 'myLongWord'
.join(''); //spojí ['', 'Dlouhé', 'Slovo']do 'méDlouhéSlovo'
}
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
describe("camelize", function() {
describe("camelizace", function() {

it("leaves an empty line as is", function() {
assert.equal(camelize(""), "");
it("prázdný řádek nechá tak, jak je", function() {
assert.equal(camelizace(""), "");
});

it("turns background-colorinto backgroundColor", function() {
assert.equal(camelize("background-color"), "backgroundColor");
it("změní background-colorna backgroundColor", function() {
assert.equal(camelizace("background-color"), "backgroundColor");
});

it("turns list-style-imageinto listStyleImage", function() {
assert.equal(camelize("list-style-image"), "listStyleImage");
it("změní list-style-imagena listStyleImage", function() {
assert.equal(camelizace("list-style-image"), "listStyleImage");
});

it("turns -webkit-transitioninto WebkitTransition", function() {
assert.equal(camelize("-webkit-transition"), "WebkitTransition");
it("změní -webkit-transitionna WebkitTransition", function() {
assert.equal(camelizace("-webkit-transition"), "WebkitTransition");
});

});
16 changes: 8 additions & 8 deletions1-js/05-data-types/05-array-methods/1-camelcase/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,18 +2,18 @@ importance: 5

---

#Translate border-left-widthto borderLeftWidth
#Změňte border-left-widthna borderLeftWidth

Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString".
Napište funkci `camelizace(řetězec)`, která změní slova oddělená pomlčkou, např. „můj-krátký-řetězec“, na velbloudí notaci „můjKrátkýŘetězec“.

That is: removes all dashes, each word after dash becomes uppercased.
To znamená, že odstraní všechny pomlčky a u všech slov za pomlčkami změní první písmeno na velké.

Examples:
Příklad:

```js
camelize("background-color") == 'backgroundColor';
camelize("list-style-image") == 'listStyleImage';
camelize("-webkit-transition") == 'WebkitTransition';
camelizace("background-color") == 'backgroundColor';
camelizace("list-style-image") == 'listStyleImage';
camelizace("-webkit-transition") == 'WebkitTransition';
```

P.S.Hint: use `split`to split the string into an array, transform it and`join` back.
P.S.Rada: použijte `split`pro rozdělení řetězce na pole, přeměňte je a spojte zpět pomocí`join`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
```js run
functiongetAverageAge(users) {
returnusers.reduce((prev, user) =>prev +user.age, 0) /users.length;
functionvraťPrůměrnýVěk(uživatelé) {
returnuživatelé.reduce((předchozí, uživatel) =>předchozí +uživatel.věk, 0) /uživatelé.length;
}

letjohn = {name: "John",age: 25 };
letpete = {name: "Pete",age: 30 };
letmary = {name: "Mary",age: 29 };
letjan = {jméno: "Jan",věk: 25 };
letpetr = {jméno: "Petr",věk: 30 };
letmarie = {jméno: "Marie",věk: 29 };

letarr = [john, pete, mary ];
letpole = [jan, petr, marie ];

alert(getAverageAge(arr) ); // 28
alert(vraťPrůměrnýVěk(pole) ); // 28
```

18 changes: 9 additions & 9 deletions1-js/05-data-types/05-array-methods/10-average-age/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,20 +2,20 @@ importance: 4

---

#Get average age
#Zjištění průměrného věku

Write the function `getAverageAge(users)` that gets an array of objects with property `age` and returns the average age.
Napište funkci `vraťPrůměrnýVěk(uživatelé)`, která obdrží pole objektů s vlastností `věk` a vrátí průměrný věk.

The formula for the average is `(age1 +age2 + ... +ageN) / N`.
Vzorec pro výpočet průměru je `(věk1 +věk2 + ... +věkN) / N`.

For instance:
Příklad:

```js no-beautify
letjohn = {name: "John",age: 25 };
letpete = {name: "Pete",age: 30 };
letmary = {name: "Mary",age: 29 };
letjan = {jméno: "Jan",věk: 25 };
letpetr = {jméno: "Petr",věk: 30 };
letmarie = {jméno: "Marie",věk: 29 };

letarr = [john, pete, mary ];
letpole = [jan, petr, marie ];

alert(getAverageAge(arr) ); // (25 + 30 + 29) / 3 = 28
alert(vraťPrůměrnýVěk(pole) ); // (25 + 30 + 29) / 3 = 28
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
functionunique(arr) {
letresult = [];
functionunikát(pole) {
letvýsledek = [];

for (letstr ofarr) {
if (!result.includes(str)) {
result.push(str);
for (letřetězec ofpole) {
if (!výsledek.includes(řetězec)) {
výsledek.push(řetězec);
}
}

returnresult;
returnvýsledek;
}
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
describe("unique", function() {
it("removes non-unique elements", function() {
letstrings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
describe("unikát", function() {
it("odstraní neunikátní prvky", function() {
letřetězce = ["Haré", "Kršna", "Haré", "Kršna",
"Kršna", "Kršna", "Haré", "Haré", ":-O"
];

assert.deepEqual(unique(strings), ["Hare", "Krishna", ":-O"]);
assert.deepEqual(unikát(řetězce), ["Haré", "Kršna", ":-O"]);
});

it("does not change the source array", function() {
letstrings = ["Krishna", "Krishna", "Hare", "Hare"];
unique(strings);
assert.deepEqual(strings, ["Krishna", "Krishna", "Hare", "Hare"]);
it("nemění zdrojové pole", function() {
letřetězce = ["Kršna", "Kršna", "Haré", "Haré"];
unikát(řetězce);
assert.deepEqual(řetězce, ["Kršna", "Kršna", "Haré", "Haré"]);
});
});
40 changes: 20 additions & 20 deletions1-js/05-data-types/05-array-methods/11-array-unique/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
Let's walk the array items:
-For each item we'll check if the resulting array already has that item.
-If it is so, then ignore, otherwise add to results.
Projděme si prvky pole:
-U každého prvku ověříme, zda výsledné pole již tento prvek obsahuje.
-Pokud je tomu tak, budeme ho ignorovat, jinak ho přidáme do výsledku.

```js run demo
functionunique(arr) {
letresult = [];
functionunikát(pole) {
letvýsledek = [];

for (letstr ofarr) {
if (!result.includes(str)) {
result.push(str);
for (letřetězec ofpole) {
if (!výsledek.includes(řetězec)) {
výsledek.push(řetězec);
}
}

returnresult;
returnvýsledek;
}

letstrings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
letřetězce = ["Haré", "Kršna", "Haré", "Kršna",
"Kršna", "Kršna", "Haré", "Haré", ":-O"
];

alert(unique(strings) ); //Hare, Krishna, :-O
alert(unikát(řetězce) ); //Haré, Kršna, :-O
```

The code works, but there's a potential performance problem in it.
Tento kód funguje, ale má potenciální problém s výkonem.

The method `result.includes(str)`internally walks the array `result` and compares each element against `str` to find the match.
Metoda `výsledek.includes(řetězec)`vnitřně prochází pole `výsledek` a porovná každý jeho prvek s `řetězec`, aby našla shodu.

So if there are `100` elements in `result` and no one matches `str`,then it will walk the whole `result` and do exactly `100`comparisons. And if `result` is large, like `10000`,then there would be`10000`comparisons.
Jestliže tedy v poli `výsledek` je `100` prvků a žádný se nerovná `řetězec`,pak projde celé pole `výsledek` a provede právě `100`porovnání. A je-li `výsledek` velký, např. `10000`,pak se vykoná`10000`porovnání.

That's not a problem by itself, because JavaScript engines are very fast, so walk`10000`array is a matter of microseconds.
To samo o sobě není problém, jelikož JavaScriptové motory jsou velmi rychlé, takže projít pole`10000`prvků je otázkou mikrosekund.

But we do such testfor each element of `arr`, in the `for` loop.
My však provádíme takový testpro každý prvek `pole` v cyklu `for`.

So if `arr.length`is `10000` we'll have something like `10000*10000` = 100millions of comparisons. That's a lot.
Jestliže tedy `pole.length`je `10000`, budeme mít něco jako `10000*10000` = 100miliónů porovnání. To je hodně.

So the solution is only good for small arrays.
Toto řešení je tedy dobré jen pro malá pole.

Further in the chapter<info:map-set>we'll see how to optimize it.
Později v kapitole<info:map-set>uvidíme, jak je optimalizovat.
18 changes: 9 additions & 9 deletions1-js/05-data-types/05-array-methods/11-array-unique/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,22 +2,22 @@ importance: 4

---

#Filter unique array members
#Filtrace unikátních prvků pole

Let `arr` be an array.
Nechť `pole` je nějaké pole.

Create a function `unique(arr)` that should return an array with unique items of `arr`.
Vytvořte funkci `unikát(pole)`, která vrátí pole obsahující všechny různé prvky `pole`.

For instance:
Příklad:

```js
functionunique(arr) {
/*your code */
functionunikát(pole) {
/*váš kód */
}

letstrings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
letřetězce = ["Haré", "Kršna", "Haré", "Kršna",
"Kršna", "Kršna", "Haré", "Haré", ":-O"
];

alert(unique(strings) ); //Hare, Krishna, :-O
alert(unikát(řetězce) ); //Haré, Kršna, :-O
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
functiongroupById(array) {
returnarray.reduce((obj,value) => {
obj[value.id] =value;
functionseskupPodleId(pole) {
returnpole.reduce((obj,hodnota) => {
obj[hodnota.id] =hodnota;
return obj;
}, {})
}
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
describe("groupById", function() {
describe("seskupPodleId", function() {

it("creates an object grouped by id", function() {
letusers = [
{id: 'john',name: "John Smith",age: 20},
{id: 'ann',name: "Ann Smith",age: 24},
{id: 'pete',name: "Pete Peterson",age: 31},
it("vytvoří objekt seskupený podle id", function() {
letuživatelé = [
{id: 'jan',jméno: "Jan Novák",věk: 20},
{id: 'anna',jméno: "Anna Nováková",věk: 24},
{id: 'petr',jméno: "Petr Petřík",věk: 31},
];

assert.deepEqual(groupById(users), {
john: {id: 'john',name: "John Smith",age: 20},
ann: {id: 'ann',name: "Ann Smith",age: 24},
pete: {id: 'pete',name: "Pete Peterson",age: 31},
assert.deepEqual(seskupPodleId(uživatelé), {
jan: {id: 'jan',jméno: "Jan Novák",věk: 20},
anna: {id: 'anna',jméno: "Anna Nováková",věk: 24},
petr: {id: 'petr',jméno: "Petr Petřík",věk: 31},
});
});

it("works with an empty array", function() {
users = [];
assert.deepEqual(groupById(users), {});
it("funguje s prázdným polem", function() {
uživatelé = [];
assert.deepEqual(seskupPodleId(uživatelé), {});
});
});
34 changes: 17 additions & 17 deletions1-js/05-data-types/05-array-methods/12-reduce-object/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,36 +2,36 @@ importance: 4

---

#Create keyed object from array
#Vytvoření klíčovaného objektu z pole

Let's say we received an array of users in the form`{id:...,name:...,age:... }`.
Řekněme, že jsme získali pole uživatelů ve formě`{id:...,jméno:...,věk... }`.

Create a function `groupById(arr)` that creates an object from it, with`id`as the key, and array items as values.
Vytvořte funkci `seskupPodleId(pole)`, která z něj vytvoří objekt, jehož klíči budou hodnoty`id`a hodnotami prvky pole.

For example:
Příklad:

```js
letusers = [
{id: 'john',name: "John Smith",age: 20},
{id: 'ann',name: "Ann Smith",age: 24},
{id: 'pete',name: "Pete Peterson",age: 31},
letuživatelé = [
{id: 'jan',jméno: "Jan Novák",věk: 20},
{id: 'anna',jméno: "Anna Nováková",věk: 24},
{id: 'petr',jméno: "Petr Petřík",věk: 31},
];

letusersById =groupById(users);
letuživateléPodleId =seskupPodleId(uživatelé);

/*
//after the call we should have:
//po volání bychom měli mít:

usersById = {
john: {id: 'john',name: "John Smith",age: 20},
ann: {id: 'ann',name: "Ann Smith",age: 24},
pete: {id: 'pete',name: "Pete Peterson",age: 31},
uživateléPodleId = {
jan: {id: 'jan',jméno: "Jan Novák",věk: 20},
anna: {id: 'anna',jméno: "Anna Nováková",věk: 24},
petr: {id: 'petr',jméno: "Petr Petřík",věk: 31},
}
*/
```

Such function is really handy when working with server data.
Taková funkce se opravdu hodí, když pracujeme se serverovými daty.

In this task we assume that`id`is unique. There may be no two array items with the same `id`.
V této úloze předpokládáme, že`id`je unikátní. V poli nesmějí být dva prvky se stejným `id`.

Please use array`.reduce` method in the solution.
Prosíme použijte v řešení metodu pole`.reduce`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@

functionfilterRange(arr, a, b) {
//added brackets around the expression for better readability
returnarr.filter(item => (a <=item &&item <= b));
functionfiltrujPodleRozsahu(pole, a, b) {
//závorky kolem výrazu jsou přidány pro lepší čitelnost
returnpole.filter(prvek => (a <=prvek &&prvek <= b));
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp