Skip to content

Instantly share code, notes, and snippets.

@kianurivzzz
Last active June 9, 2024 10:52
Show Gist options
  • Save kianurivzzz/d01371152b84a455256faaa2b96750df to your computer and use it in GitHub Desktop.
Save kianurivzzz/d01371152b84a455256faaa2b96750df to your computer and use it in GitHub Desktop.
// Для примеров
let i = 1;
let j = 1;
const getSecondElement = () => 1;
const items = []; // Пустой Массив
const friends = ['Petya', 'Vasya', 'Ivan']; // Заполненный массив
const matrix = [
[1, 2, 3],
['один', 'два', 'три'],
];
console.log(friends[0]); // Обращение по индексу
console.log(friends[i]);
console.log(friends[i + j]);
console.log(friends[getSecondElement()]);
console.log(friends.length); // длинна массива
console.log(friends[friends.length - 1]); // последний элемент массива
console.log(friends.at(0));
console.log(friends.at(-1));
// Измение элемента массива
const animals = ['cats', 'dogs', 'birds'];
animals[0] = 'horses';
console.log(animals);
animals[2] = 'fish';
console.log(animals);
// Можно менять значение данных, но нельзя менять ссылку. В этом примере будет
animals = ['fish', 'cats'];
// Добавление элементов в массив
const animals = ['cats', 'dogs', 'birds'];
animals.push('horses');
// Массив animals поменялся
console.log(animals);
// Строка 'horses' добавилась в конец массива
console.log(animals[3]);
animals.unshift('fish');
console.log(animals[0]);
animals[4] = 'cows';
console.log(animals);
// Удаление элементов массива
const animals = ['cats', 'dogs', 'birds'];
delete animals[1];
console.log(animals);
console.log(animals.length);
// Проверка на существование элемента массива
const animals = ['cats', 'dogs', 'birds'];
const index = 2;
if (index < animals.length) {
console.log(animals[index]);
};
// Обход элементов массива
const userNames = ['petya', 'vasya', 'sasha'];
for (let i = 0; i < userNames.length; i++) {
console.log(userNames[i]);
}
console.log('----');
for (let i = 0; i < userNames.length; i++) {
const index = userNames.length - 1 - i;
console.log(userNames[index]);
}
console.log('----');
for (let i = userNames.length - 1; i >= 0; i--) {
console.log(userNames[i]);
}
const emails = ['[email protected]', '[email protected]', '[email protected]'];
console.log(emails);
for (let i = 0; i < emails.length; i++) {
const email = emails[i];
const normalizedEmail = email.toLowerCase();
emails[i] = normalizedEmail;
}
console.log(emails);
// Агрегация данных
// поиск максимального значения
const findMaxItem = array => {
if (array.length === 0) {
return null;
}
let max = array[0];
for (let i = 1; i < array.length; i++) {
const currentElement = array[i];
if (currentElement > max) {
max = currentElement;
}
}
return max;
};
// сумма элементов
const calculateSum = array => {
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
};
console.log(findMaxItem([])); // null
console.log(findMaxItem([3, 2, -10, 37, 0])); // 37
console.log(calculateSum([])); // 0
console.log(calculateSum([3, 2, -10, 38, 0])); // 33
// Реализуйте функцию. Она должна высчитывать сумму всех элементов массива, которые делятся без остатка на три:
const coll1 = [8, 9, 21, 19, 18, 22, 7];
calculateSum(coll1); // 48
const coll2 = [2, 0, 17, 3, 9, 15, 4];
calculateSum(coll2); // 27
// В случае пустого массива функция должна вернуть 0 (для этого в коде можно использовать guard expression):
const coll = [];
calculateSum(coll); // 0
const compact = array => {
const result = [];
for (const item of array) {
if (item !== null) {
result.push(item);
}
}
return result;
};
console.log(compact([0, 1, false, null, true, 'wow', true, null]));
const array = ['one', 'two', 'three', 'four', 'stop', 'five'];
// подходит
for (const item of array) {
if (item === 'stop') {
break;
}
console.log(item);
}
// не подходит
let i = 0;
while (array[i] !== 'stop') {
console.log(array[i]);
i += 1;
}
const myCompact = array => {
const result = [];
for (const item of array) {
if (item === null) {
continue;
}
result.push(item);
}
return result;
};
const str = 'some text';
str.slice(1, 6); // 'ome t'
str.slice(7); // 'xt'
const getTotalAmount = (wallet, currency) => {
let sumMoney = 0;
for (const money of wallet) {
const splitMoney = money.split(' '); // 'eur 10' =>['eur', '10']
if (splitMoney[0] === currency) {
sumMoney += Number(splitMoney[1]);
}
}
return sumMoney;
};
const money3 = [
'eur 10',
'rub 50',
'eur 5',
'rub 10',
'rub 10',
'eur 100',
'rub 200',
];
console.log(getTotalAmount(money3, 'rub'));
const array = [[3]];
console.log(array.length);
const array2 = [1, [3, 2], [3, [4]]];
console.log(array2.length);
console.log(array[0][0]);
console.log(array2[2][1][0]);
array[0] = [2, 1];
array.push([3, 4, 5]);
console.log(array);
array[0][0] = 5;
console.log(array);
const field = [
[null, null, null],
[null, null, null],
[null, null, null],
];
const hasPlayerMove = (field, symbol) => {
for (const row of field) {
if (row.includes(symbol)) {
return true;
}
}
return false;
};
field[0][1] = 'x';
console.log(hasPlayerMove(field, 'x'));
console.log(field);
const buildHTMLList = coll => {
const parts = [];
for (const item of coll) {
parts.push(`<li>${item}</li>`);
}
// Метод join объединяет элементы массива в строку
// В качестве разделителя между значениями
// используется то, что передано параметром
const innerValue = parts.join('\n');
const result = `<ul>${innerValue}</ul>`;
return result;
};
const coll = ['milk', 'butter'];
console.log(buildHTMLList(coll));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment