Advanced Array Methods
Array.findIndex()
Section titled “Array.findIndex()”Diese Methode findet den Index eines bestimmten Elements. Sie loopt durch jedes Element im Array und gibt den ersten truthy Wert zurück.
Vereinfacht gesagt macht die Methode eine interne if-Abfrage.
Array.findIndex(currentItem, index); // index is optional
const index = array.findIndex((currentItem, index) => { // return a truthy expression here});
const cats = [ { name: 'Scooty' }, { name: 'Pye'}, { name: 'Pedro' }, { name: 'Carolina'},];// zur Verdeutlichung geben wir hier einmal die "Ergebnisse" mit der Konsole aus:// console.log gibt (im Gegensatz zu return) keinen Wert zurück!const pedroIndex = cats.findIndex(cat => console.log(cat.name === 'Pedro'));// false// false// true// false
// dasselbe Beispiel mit einem impliziten return:// zurückgegeben wird der Index, bei dem der Ausdruck truthy ist// anschließend bricht die Schleife abconst pedroIndex = cats.findIndex(cat => cat.name === 'Pedro');console.log(pedroIndex); // 2// vereinfacht gesagt: if (cat.name === 'Pedro') return index of PedroArray.find()
Section titled “Array.find()”array.find() funktioniert genauso wie array.findIndex(), gibt aber das Element zurück.
const pedroName = cats.find(cat => cat.name === 'Pedro');console.log(pedroName); // object { name: 'Pedro' };// vereinfacht gesagt: if (cat.name === 'Pedro') return the whole itemArray.filter()
Section titled “Array.filter()”Syntax
Array.prototype.filter(callback(element[, index[, array]][, thisArg]))
array.filter() gibt einen neuen Array zurück. Der neue Array ist ein Subset des ursprünglichen Arrays. Ein Element wird zum neuen Array hinzugefügt, wenn ein “truthy” Ausdruck zurückgegeben wird.
const filteredItems = Array.filter((currentItem, index) => { // return a truthy expression to include in filtered items});
const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6];const biggerThan10 = numbers.filter(number => { if (number > 10) return true;});console.log(biggerThan10); // 12, 18, 11, 50// shorter version:// just return the if-condition because a truthy expression evaluates to trueconst biggerThan10 = numbers.filter(number => number > 10);console.log(biggerThan10); // 12, 18, 11, 50Array.map()
Section titled “Array.map()”array.map() gibt einen neuen Array zurück, der dieselbe Anzahl von Elementen besitzt wie der ursprüngliche Array. Jedes Element im neuen Array ist der Wert, der von der Callback-Funktion zurückgegeben wird.
const newArray = Array.map((currentItem, index) => { // return the transformed value});
const multipliedBy5 = numbers.map(number => { return number * 5;});// with implicit return:const multipliedBy5 = numbers.map(number => number * 5);
const todos = ['buy eggs', 'feed my cat', 'water plants'];const todoStrings = todos.map(todo => `I need to ${todo}`);console.log(todoStrings);console.log(...todoStrings);
const people = [ { firstName: 'Peter', lastName: 'Alexander' }, { firstName: 'Waltraud', lastName: 'Haas' }];
const firstNames = people.map(person => person.firstName);console.log(firstNames);map vs. forEach?
Section titled “map vs. forEach?”Use array.map() to return a new array.
Use array.foreach() to get stuff done.
Array.join()
Section titled “Array.join()”join macht aus einem Array einen String. Wenn join ohne Argument aufgerufen wird, werden die einzelnen Elemente mit einem Beistrich verbunden.
Das will man oft nicht, daher wählt man als Trenner einen empty string: join('').
const devs = ['Addy Osmani', ' Vitaly Friedman', 'Chris Coyer'];const string = devs.join();console.log(string); // Addy Osmani,Vitaly Friedman,Chris Coyer
// nun mit empty string als Trennzeichen:const string = devs.join('');console.log(string); // Addy OsmaniVitaly FriedmanChris CoyerMit diesem Ergebnis können wir weitermachen: ein häufig vorkommender use case ist, dass die Elemente im Array als Listenpunkte ausgegeben werden:
Elemente im Array als Listenpunkte ausgeben
Array.reduce()
Section titled “Array.reduce()”array.reduce() is a method which helps to convert an array into a single value.
const callback = (accumulator, currentValue, index) => { // return something here}const result = array.reduce(callback, initialValue);const result = array.reduce((acc, currVal) => {}, initialValue);Example 1: summing numbers
Section titled “Example 1: summing numbers”const numbers = [1, 2, 3, 4, 5];const total = numbers.reduce((acc, num) => acc + num, 0);const totalLongVersion = numbers.reduce((acc, num) => { return acc + num;}, 0);console.log(total);Example 2: reducing an array into an object
Section titled “Example 2: reducing an array into an object”const fruits = ['apple', 'apple', 'banana', 'banana', 'orange', 'pear', 'apple'];Now we want to know the number of each type of fruit:
- pass an empty object as the initial value:
const tally = fruits.reduce((accumulator, fruit) => { // do sth.}, {});In the first iteration, the accumulator will be {}, fruit will be apple. Add apple to the accumulator and set the number of apples to 1:
const tally = fruits.reduce((accumulator, fruit) => { return (accumulator[fruit] = 1);}, {});In the second iteration, the accumulator is { apple: 1 }, fruit: apple. Now we want to increase the number of apples in the accumulator. To do so, we need to check if the apple property exists in acc.
If yes, we increase the value by 1:
const tally = fruits.reduce((accumulator, fruit) => { if (accumulator[fruit]) { accumulator[fruit] = accumulator[fruit] + 1; } else { accumulator[fruit] = 1; } return accumulator;}, {});Now alltogether:
const tally = fruits.reduce((accumulator, fruit) => { const fruitCount = accumulator[fruit]; fruitCount ? (accumulator[fruit] = fruitCount + 1) : (accumulator[fruit] = 1); return accumulator;}, {});Chaining array methods
Section titled “Chaining array methods”Die Methoden map() und filter() geben wieder Arrays zurück, daher können sie mit weiteren map() und filter() Methoden verkettet werden. Um die Methoden zu verketten, kann die zweite Methode einfach an die erste angehängt werden:
const chainedMethods = numbers .map(number => number * 5) .filter(number => number >= 20 && number <= 40);Excercise
Section titled “Excercise”const people2 = [ { firstName: 'Benjamin', lastName: 'Franklin', yearBorn: 1706, yearOfDeath: 1790, }, { firstName: 'Thomas', lastName: 'Edison', yearBorn: 1847, yearOfDeath: 1931, }, { firstName: 'Franklin', lastName: 'Roosevelt', yearBorn: 1882, yearOfDeath: 1945, }, { firstName: 'Napoleon', lastName: 'Bonaparte', yearBorn: 1769, yearOfDeath: 1821, }, { firstName: 'Abraham', lastName: 'Lincoln', yearBorn: 1809, yearOfDeath: 1865, }, { firstName: 'Mahatma', lastName: 'Gandhi', yearBorn: 1869, yearOfDeath: 1948, }, { firstName: 'Winston', lastName: 'Churchill', yearBorn: 1874, yearOfDeath: 1965, }, { firstName: 'Charles', lastName: 'Darwin', yearBorn: 1809, yearOfDeath: 1882, }, { firstName: 'Albert', lastName: 'Einstein', yearBorn: 1879, yearOfDeath: 1955, }, { firstName: 'Pablo', lastName: 'Picasso', yearBorn: 1881, yearOfDeath: 1973, }, { firstName: 'Ludwig', lastName: 'Beethoven', yearBorn: 1770, yearOfDeath: 1827, }, { firstName: 'Walt', lastName: 'Disney', yearBorn: 1901, yearOfDeath: 1966 }, { firstName: 'Henry', lastName: 'Ford', yearBorn: 1863, yearOfDeath: 1947 }, { firstName: 'Steve', lastName: 'Jobs', yearBorn: 1955, yearOfDeath: 2012 },]// 1. find the index of Thomas Edisonconst indexOfEdison = people2.findIndex(person => person.firstName === 'Thomas' && person.lastName === 'Edison');console.log(indexOfEdison);// 2. find the object that contains Winston Churchillconst winstonChurchill = people2.find(person => person.firstName === 'Winston' && person.lastName === 'Churchill');console.log(winstonChurchill);// 3. Create an array of people who died before 1940const diedBefore1940 = people2.filter(person => person.yearOfDeath < 1940);console.log(...diedBefore1940);// 4. Create an array of people who were alive between 1850 and 1970const aliveBetween = people2.filter(person => person.yearBorn > 1850 && person.yearOfDeath < 1970);console.log(...aliveBetween);// 5. Create an array that contains the firstName, lastName and yearsLived for each person (yearsLived is the number of years the person lived)const yearsLived = people2.map(person => `${person.firstName} ${person.lastName} lived ${(person.yearOfDeath - person.yearBorn)} years.`);console.log(...yearsLived);// 6. Get the total number of yearsLived of the people who were alive between 1790 and 1900const aliveBetween2 = people2.filter(person => person.yearBorn > 1750 && person.yearOfDeath < 1900);console.log(...aliveBetween2);
const age = aliveBetween2.map(person => person.yearOfDeath - person.yearBorn);console.log(age);
function sumAges(age) { let ageTotal = 0; age.forEach(a => { ageTotal = ageTotal + a; // ageTotal += a; }); console.log(ageTotal);};sumAges(age);