Skip to content

Commit 404c4ee

Browse files
committed
[EX-11.8.1/st-compl] searching-definite-value
Searching "definite" value.. by for(), filter().. then by some() meth. Worth noting: - that all/this variants "found", but not all of them.. optimal. FS-dev: B-3 / JS basic
1 parent 34cbbc7 commit 404c4ee

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

  • full-stack-dev/3-js-basic/11-arrays-iterations/11-8-1-ex-searching-definite-value
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Нужно сразу написать функцию some, которая возвращает true, если такое значение/элемент есть, и false, если его нет в искомом массиве. Внутри функции можно использовать или цикл for, или методы filter(), или find().
2+
// const arr = [2, 4, 4, 10, 20];
3+
// А после этого, как альтернативное решение.. нужно отработать поиск посредствам метода some().
4+
5+
const arr = [2, 4, 4, 10, 20];
6+
const definiteNum = 20;
7+
8+
// через цикл for()
9+
function some(value, arr) {
10+
for (const num of arr) {
11+
if (num === value) {
12+
return true;
13+
}
14+
}
15+
16+
return false;
17+
}
18+
19+
console.log(some(definiteNum, arr)); // true
20+
21+
// через метод filter() ..можно, НО не рекомендуется
22+
function someWithFilter(arr, value) {
23+
const filteredArr = arr.filter((num) => num === value);
24+
return filteredArr.length > 0; // если длина нового массива > 0, значит.. элемент(ы) были найдены
25+
}
26+
27+
console.log(someWithFilter(arr, definiteNum)); // true
28+
29+
// через метод find()
30+
function someWithFind(arr, value) {
31+
const result = arr.find((num) => num === value);
32+
// return !!result; // перевод результат в boolean, т.е. find() возвращает или сам элемент или undefined (а если нужно найти undefined)
33+
return result === undefined ? false : true; // так с undefined проблем не будет
34+
}
35+
36+
console.log(someWithFind(arr, definiteNum)); // true
37+
38+
// через метод findIndex()
39+
function someWithFindIndex(arr, value) {
40+
const index = arr.findIndex((item) => item === value);
41+
return index !== -1; // проблем с поиском undefined не будет..
42+
}
43+
44+
console.log(someWithFindIndex(arr, definiteNum)); // true
45+
46+
// ?? через метод some()
47+
const hasDefiniteNum = arr.some((num) => num === definiteNum);
48+
console.log(hasDefiniteNum); // true

0 commit comments

Comments
 (0)