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#192

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
tarasyyyk merged 29 commits intojavascript-tutorial:masterfromRegnised:master
Aug 25, 2021
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
29 commits
Select commitHold shift + click to select a range
a11e2a3
Objects
RegnisedAug 14, 2021
d073b92
Merge branch 'javascript-tutorial:master' into master
RegnisedAug 14, 2021
6f63dff
Update 1-js/04-object-basics/01-object/2-hello-object/task.md
RegnisedAug 15, 2021
690516f
Update 1-js/04-object-basics/01-object/3-is-empty/task.md
RegnisedAug 15, 2021
d1d20f9
Update 1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/te…
RegnisedAug 15, 2021
126b55b
Update 1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/te…
RegnisedAug 15, 2021
1808c2f
Update 1-js/04-object-basics/01-object/article.md
RegnisedAug 15, 2021
b7f4746
Update 1-js/04-object-basics/01-object/article.md
RegnisedAug 15, 2021
c31ff51
Update 1-js/04-object-basics/01-object/2-hello-object/task.md
tarasyyykAug 15, 2021
68d53eb
Update 1-js/04-object-basics/01-object/2-hello-object/task.md
tarasyyykAug 15, 2021
019602e
Update 1-js/04-object-basics/01-object/2-hello-object/task.md
tarasyyykAug 15, 2021
550b1fb
Objects
RegnisedAug 23, 2021
787568b
Merge branch 'master' of github.com:Regnised/uk.javascript.info
RegnisedAug 23, 2021
82f0f9a
Merge branch 'javascript-tutorial:master' into master
RegnisedAug 23, 2021
cbda1c0
Update 1-js/05-data-types/05-array-methods/1-camelcase/task.md
tarasyyykAug 23, 2021
3f73a4b
Update 1-js/05-data-types/05-array-methods/10-average-age/task.md
RegnisedAug 24, 2021
007d5ac
Update 1-js/05-data-types/05-array-methods/11-array-unique/solution.md
RegnisedAug 24, 2021
0a58cb5
Update 1-js/05-data-types/05-array-methods/12-reduce-object/task.md
RegnisedAug 24, 2021
15efbc0
Update 1-js/05-data-types/05-array-methods/9-shuffle/task.md
RegnisedAug 24, 2021
7758975
Update 1-js/05-data-types/05-array-methods/9-shuffle/solution.md
RegnisedAug 24, 2021
ca0c3b0
Update 1-js/05-data-types/05-array-methods/2-filter-range/task.md
RegnisedAug 24, 2021
86fccb4
Update 1-js/05-data-types/05-array-methods/2-filter-range/task.md
RegnisedAug 24, 2021
1ea7283
Update 1-js/05-data-types/05-array-methods/3-filter-range-in-place/ta…
RegnisedAug 24, 2021
676d942
Update 1-js/05-data-types/05-array-methods/7-map-objects/task.md
RegnisedAug 24, 2021
eff8fea
Add translate
RegnisedAug 24, 2021
5cb6b18
Merge branch 'master' of github.com:Regnised/uk.javascript.info
RegnisedAug 24, 2021
4a1c393
Merge branch 'javascript-tutorial:master' into master
RegnisedAug 24, 2021
c987f1d
Update 1-js/05-data-types/05-array-methods/9-shuffle/solution.md
tarasyyykAug 25, 2021
b5a26f7
Update 1-js/05-data-types/05-array-methods/9-shuffle/solution.md
tarasyyykAug 25, 2021
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 @@
function camelize(str) {
return str
.split('-') //splits 'my-long-word'into array ['my', 'long', 'word']
.split('-') //розбиваємо 'my-long-word'на масив елементів ['my', 'long', 'word']
.map(
//capitalizes first letters of all array items except the first one
//converts ['my', 'long', 'word']into ['my', 'Long', 'Word']
//робимо першу літеру велику для всіх елементів масиву, крім першого
//конвертуємо ['my', 'long', 'word']в ['my', 'Long', 'Word']
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
)
.join(''); //joins ['my', 'Long', 'Word']into 'myLongWord'
.join(''); //зʼєднуємо ['my', 'Long', 'Word']в 'myLongWord'
}
10 changes: 5 additions & 5 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

---

#Translateborder-left-widthto borderLeftWidth
#Переведіть текст видуborder-left-widthв borderLeftWidth

Write the function`camelize(str)` that changes dash-separated words like"my-short-string"into camel-cased "myShortString".
Напишіть функцію`camelize(str)`, яка перетворює такі рядки"my-short-string"в "myShortString".

That is: removes all dashes, each word after dash becomes uppercased.
Тобто дефіси видаляються, а всі слова після них починаються з великої літери.

Examples:
Приклади:

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

P.S.Hint: use `split` to split the string into an array, transform it and`join`back.
P.S.Підказка: використовуйте `split`, щоб розбити рядок на масив символів, потім переробіть все як потрібно та методом`join`зʼєднайте елементи в рядок.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,11 +3,11 @@ function getAverageAge(users) {
return users.reduce((prev, user) => prev + user.age, 0) / users.length;
}

letjohn = { name: "John", age: 25 };
letpete = { name: "Pete", age: 30 };
letmary = { name: "Mary", age: 29 };
letivan = { name: "Іван", age: 25 };
letpetro = { name: "Петро", age: 30 };
letmariya = { name: "Марія", age: 29 };

let arr = [john, pete, mary ];
let arr = [ivan, petro, mariya ];

alert( getAverageAge(arr) ); // 28
```
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,13 +2,13 @@ importance: 4

---

#Get average age
#Вирахувати середній вік

Write the function`getAverageAge(users)` that gets an array of objects with property`age`and returns the average age.
Напишіть функцію`getAverageAge(users)`, яка приймає масив об’єктів з властивістю`age`та повертає середній вік.

The formula for the average is `(age1 + age2 + ... + ageN) / N`.
Формула обчислення середнього арифметичного значення: `(age1 + age2 + ... + ageN) / N`.

For instance:
Наприклад:

```js no-beautify
let john = { name: "John", age: 25 };
Expand Down
28 changes: 14 additions & 14 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,6 +1,6 @@
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.
Давайте пройдемося по елементам масиву:
-Для кожного елемента ми перевіримо, чи є він в масиві з результатом.
-Якщо є, то ігноруємо його, а якщо немає -- додаємо до результатів.

```js run demo
function unique(arr) {
Expand All@@ -15,25 +15,25 @@ function unique(arr) {
return result;
}

let strings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
let strings = ["Привіт", "Світ", "Привіт", "Світ",
"Привіт", "Привіт", "Світ", "Світ", ":-O"
];

alert( unique(strings) ); //Hare, Krishna, :-O
alert( unique(strings) ); //Привіт, Світ, :-O
```

The code works, but there's a potential performance problem in it.
Код працює, але в ньому є потенційна проблема з продуктивністю.

The method`result.includes(str)`internally walks the array `result`and compares each element against `str` to find the match.
Метод`result.includes(str)`всередині себе обходить масив `result`і порівнює кожен елемент з `str`, щоб знайти збіг.

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.
Таким чином, якщо `result` містить`100`елементів і жоден з них не збігається з`str`,тоді він обійде весь`result`і зробить рівно `100`порівнянь. А якщо `result`великий масив, наприклад, `10000` елементів, то буде зроблено`10000`порівнянь.

That's not a problem by itself, becauseJavaScriptengines are very fast, so walk `10000`array is a matter of microseconds.
Само собою це не проблема, адже рушійJavaScriptдуже швидкий, тому обхід `10000`елементів масиву займає лічені мікросекунди.

But we do such test for each element of`arr`, in the `for` loop.
Але ми робимо таку перевірку для кожного елемента`arr` в циклі `for`.

So if `arr.length`is `10000` we'll have something like`10000*10000` = 100millions of comparisons. That's a lot.
Тому, якщо `arr.length`дорівнює `10000`, у нас буде щось на зразок`10000*10000` = 100мільйонів порівнянь. Це забагато.

So the solution is only good for small arrays.
Ось чому дане рішення підходить тільки для невеликих масивів.

Further in the chapter<info:map-set>we'll see how to optimize it.
Далі в розділі<info:map-set>ми побачимо, як його оптимізувати.
16 changes: 8 additions & 8 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
#Залишити унікальні елементи масиву

Let `arr`be an array.
Нехай `arr`-- масив рядків.

Create a function`unique(arr)` that should return an array with unique items of `arr`.
Напишіть функцію`unique(arr)`, яка повертає масив, що містить тільки унікальні елементи `arr`.

For instance:
Наприклад:

```js
function unique(arr) {
/*your code */
/*ваш код */
}

let strings = ["Hare", "Krishna", "Hare", "Krishna",
"Krishna", "Krishna", "Hare", "Hare", ":-O"
let strings = ["Привіт", "Світ", "Привіт", "Світ",
"Привіт", "Привіт", "Світ", "Світ", ":-O"
];

alert( unique(strings) ); //Hare, Krishna, :-O
alert( unique(strings) ); //Привіт, Світ, :-O
```
28 changes: 14 additions & 14 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
#Створення об’єкта з ключем з масиву

Let's say we received an array of users in the form`{id:..., name:..., age:...}`.
Припустимо, ми отримали масив користувачів у вигляді`{id:..., name:..., age:...}`.

Create a function`groupById(arr)` that creates an object from it, with `id`as the key, and array items as values.
Створіть функцію`groupById(arr)`, яка створює з масиву об’єкт із ключом `id`та елементами масиву як значеннями.

For example:
Наприклад:

```js
let users = [
{id: 'john', name: "John Smith", age: 20},
{id: 'ann', name: "Ann Smith", age: 24},
{id: 'pete', name: "Pete Peterson", age: 31},
{id: 'іван', name: "Іван Іванко", age: 20},
{id: 'ганна', name: "Ганна Іванко", age: 24},
{id: 'петро', name: "Петро Петренко", age: 31},
];

let usersById = groupById(users);

/*
//after the call we should have:
//після виклику функції ви повинні отримати:

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},
іван: {id: 'іван', name: "Іван Іванко", age: 20},
ганна: {id: 'ганна', name: "Ганна Іванко", age: 24},
петро: {id: 'петро', name: "Петро Петренко", age: 31},
}
*/
```

Such function is really handy when working with server data.
Така функція дійсно зручна при роботі з даними сервера.

In this task we assume that `id`is unique. There may be no two array items with the same `id`.
У цьому завданні ми вважаємо, що `id`унікальний. Не може бути двох елементів масиву з однаковими `id`.

Please use array`.reduce`method in the solution.
Будь ласка, використовуйте метод масиву`.reduce` у рішенні.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@

function filterRange(arr, a, b) {
//added brackets around the expression for better readability
//навколо виразу додано дужки для кращої читабельності
return arr.filter(item => (a <= item && item <= b));
}
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
```js run demo
function filterRange(arr, a, b) {
//added brackets around the expression for better readability
//навколо виразу додано дужки для кращої читабельності
return arr.filter(item => (a <= item && item <= b));
}

let arr = [5, 3, 8, 1];

let filtered = filterRange(arr, 1, 4);

alert( filtered ); // 3,1 (matching values)
alert( filtered ); // 3,1 (відфільтровані значення)

alert( arr ); // 5,3,8,1 (not modified)
alert( arr ); // 5,3,8,1 (не змінюється)
```
12 changes: 6 additions & 6 deletions1-js/05-data-types/05-array-methods/2-filter-range/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,21 +2,21 @@ importance: 4

---

#Filter range
#Фільтрація за діапазоном

Write a function`filterRange(arr, a, b)` that gets an array`arr`,looks for elements with values higher or equal to`a`and lower or equal to`b`and return a result as an array.
Напишіть функцію`filterRange(arr, a, b)`, яка приймає масив`arr`,шукає в ньому елементи більші-рівні`a`та менші-рівні`b`і віддає масив цих елементів.

The function should not modify the array. It should return the new array.
Функція повинна повертати новий масив і не змінювати вихідний.

For instance:
Наприклад:

```js
let arr = [5, 3, 8, 1];

let filtered = filterRange(arr, 1, 4);

alert( filtered ); // 3,1 (matching values)
alert( filtered ); // 3,1 (відфільтровані значення)

alert( arr ); // 5,3,8,1 (not modified)
alert( arr ); // 5,3,8,1 (не змінюється)
```

View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) {
for (let i = 0; i < arr.length; i++) {
let val = arr[i];

//remove if outside of the interval
//видаляти, якщо не у вказаному діапазоні
if (val < a || val > b) {
arr.splice(i, 1);
i--;
Expand All@@ -15,7 +15,7 @@ function filterRangeInPlace(arr, a, b) {

let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4); //removed the numbers except from 1 to 4
filterRangeInPlace(arr, 1, 4); //видаляє всі числа крім тих, що в діапазоні від 1 до 4

alert( arr ); // [3, 1]
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,17 +2,17 @@ importance: 4

---

#Filter range "in place"
#Фільтрація за діапазоном "на місці"

Write a function`filterRangeInPlace(arr, a, b)` that gets an array`arr`and removes from it all values except those that are between `a`and `b`.The test is: `a ≤ arr[i] ≤ b`.
Напишіть функцію`filterRangeInPlace(arr, a, b)`, яка приймає масив`arr`і видаляє з нього всі значення крім тих, які знаходяться між `a`і `b`.Тобто, перевірка має вигляд `a ≤ arr[i] ≤ b`.

The function should only modify the array. It should not return anything.
Функція повинна змінювати поточний масив і нічого не повертати.

For instance:
Наприклад:
```js
let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4); //removed the numbers except from 1 to 4
filterRangeInPlace(arr, 1, 4); //видаляє всі числа крім тих, що в діапазоні від 1 до 4

alert( arr ); // [3, 1]
```
4 changes: 2 additions & 2 deletions1-js/05-data-types/05-array-methods/4-sort-back/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,12 +2,12 @@ importance: 4

---

#Sort in decreasing order
#Сортувати за спаданням

```js
let arr = [5, 2, 1, -10, 8];

// ...your code to sort it in decreasing order
// ...ваш код для сортування за спаданням

alert( arr ); // 8, 5, 2, 1, -10
```
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
We can use`slice()`to make a copy and run the sort on it:
Для копіювання масиву використовуємо`slice()`і тут же -- сортування:

```js run
function copySorted(arr) {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,17 +2,17 @@ importance: 5

---

#Copy and sort array
#Скопіювати і впорядкувати масив

We have an array of strings`arr`.We'd like to have a sorted copy of it, but keep`arr`unmodified.
У нас є масив рядків`arr`.Потрібно отримати відсортовану копію та залишити`arr`незміненим.

Create a function`copySorted(arr)` that returns such a copy.
Створіть функцію`copySorted(arr)`, яка буде повертати таку копію.

```js
let arr = ["HTML", "JavaScript", "CSS"];

let sorted = copySorted(arr);

alert( sorted ); // CSS, HTML, JavaScript
alert( arr ); // HTML, JavaScript, CSS (no changes)
alert( arr ); // HTML, JavaScript, CSS (без змін)
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
```js run

letjohn = { name: "John", age: 25 };
letpete = { name: "Pete", age: 30 };
letmary = { name: "Mary", age: 28 };
letivan = { name: "Іван", age: 25 };
letpetro = { name: "Петро", age: 30 };
letmariya = { name: "Марія", age: 28 };

let users = [john, pete, mary ];
let users = [ivan, petro, mariya ];

let names = users.map(item => item.name);

alert( names ); //John, Pete, Mary
alert( names ); //Іван, Петро, Марія
```

View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,21 +2,21 @@ importance: 5

---

#Map to names
#Трансформувати в масив імен

You have an array of `user` objects, each one has`user.name`.Write the code that converts it into an array of names.
У вас є масив об’єктівuser, і в кожному з них є`user.name`.Напишіть код, який перетворює їх в масив імен.

For instance:
Наприклад:

```js no-beautify
letjohn = { name: "John", age: 25 };
letpete = { name: "Pete", age: 30 };
letmary = { name: "Mary", age: 28 };
letivan = { name: "Іван", age: 25 };
letpetro = { name: "Петро", age: 30 };
letmariya = { name: "Марія", age: 28 };

let users = [john, pete, mary ];
let users = [ivan, petro, mariya ];

let names = /* ...your code */
let names = /* ...ваш код */

alert( names ); //John, Pete, Mary
alert( names ); //Іван, Петро, Марія
```

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@

-Please note how methods are stored. They are simply added to`this.methods` property.
-All tests and numeric conversions are done in the`calculate` method. In future it may be extended to support more complex expressions.
-Зверніть увагу, як зберігаються методи. Вони просто додаються до внутрішнього обʼєкта (`this.methods`).
-Всі тести та числові перетворення виконуються в методі`calculate`. У майбутньому він може бути розширений для підтримки складніших виразів.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp