Bugün de array metodları ile ilgili bazı egzersizler yapılacak.
Projenin demosu : Demo
Başlangıç dosyalarını bulabileceğiniz repom: js-30 | github
Çözümüm
1<script>
2// ## Array Cardio Day 2
3// ## Array Antrenmanı Gün 2
4
5const people = [
6 {name: 'Wes', year: 1988},
7 {name: 'Kait', year: 1986},
8 {name: 'Irv', year: 1970},
9 {name: 'Lux', year: 2015}
10];
11
12const comments = [
13 {text: 'Love this!', id: 523423},
14 {text: 'Super good', id: 823423},
15 {text: 'You are the best', id: 2039842},
16 {text: 'Ramen is my fav food ever', id: 123523},
17 {text: 'Nice Nice Nice!', id: 542328}
18];
19
20// Some ve Every metodları
21// Array.prototype.some() // en az bir kişi 19 yaşında veya 19'dan büyük mü?
22const yetiskinVarMi = people.some((person) => (new Date().getFullYear()) - person.year >= 19)
23console.log({yetiskinVarMi});
24
25// Array.prototype.every() // herkes 19 yaşından büyük mü?
26const herkesYetiskinMi = people.every((person) => (new Date().getFullYear()) - person.year >= 19)
27console.log({herkesYetiskinMi});
28
29// Array.prototype.find()
30// Find metodu tıpkı filter metodu gibi bir koşul alır ancak filterin aksine tam olarak istediğini elamanı seçmenizi sağlar.
31// id'si 823423 olan yorumu bulunuz
32const arananYorum = comments.find((comment) => comment.id = 823423)
33console.log(arananYorum);
34
35// Array.prototype.findIndex()
36// findIndex metodu aranan elemanın arrayde bulunduğu indexi döner
37// 823423 idli yorumun indexini findIndex ile bulup arrayden silin.
38
39const arananIndex = comments.findIndex((comment) => comment.id === 823423)
40console.log(`Aranan index = ${arananIndex}`);
41
42//splice() metodu, dizinin belirtilen index'inden başlayarak belirtilen sayıda elemanı siler ve diziyi değiştirir.
43comments.splice(arananIndex, 1)
44console.log(comments);
45
46
47</script>