Ein wichtiger Bestandteil jeder Programmiersprache. In den meisten Fällen müssen wir mehrere Operationen an Arrays ausführen, daher dieser Artikel.
In diesem Artikel möchte ich Ihnen verschiedene Methoden zum Bearbeiten von Arrays in JavaScript zeigen [^^]
Was sind Arrays in JavaScript?
Bevor wir fortfahren, müssen Sie verstehen, was Arrays wirklich bedeuten.
In JavaScript ist ein Array eine Variable, mit der verschiedene Datentypen gespeichert werden. Grundsätzlich werden verschiedene Elemente in einer Box gespeichert und können später mit der Variablen bewertet werden.Array deklarieren:
let myBox = []; // Initial Array declaration in JS
Arrays können mehrere Datentypen enthalten
let myBox = ['hello', 1, 2, 3, true, 'hi'];
Arrays können mithilfe verschiedener Aktionen bearbeitet werden, die als Methoden bezeichnet werden. Mit einigen dieser Methoden können wir Arrays hinzufügen, entfernen, ändern und noch viel mehr tun.
Ich würde dir ein paar in diesem Artikel zeigen, lass uns rollen :)
NB: Ich habe Pfeil Funktionen in diesem Beitrag Wenn Sie nicht wissen , was das bedeutet, sollten Sie hier lesen. Die Pfeilfunktion ist eine ES6-Funktion .toString ()
Die JavaScript-Methode toString()
konvertiert ein Array in eine durch Komma getrennte Zeichenfolge.
let colors = ['green', 'yellow', 'blue']; console.log(colors.toString()); // green,yellow,blue
beitreten()
Die JavaScript- join()
Methode kombiniert alle Array-Elemente zu einer Zeichenfolge.
Es ähnelt der toString()
Methode, aber hier können Sie das Trennzeichen anstelle des Standardkommas angeben.
let colors = ['green', 'yellow', 'blue']; console.log(colors.join('-')); // green-yellow-blue
concat
Diese Methode kombiniert zwei Arrays miteinander oder fügt einem Array weitere Elemente hinzu und gibt dann ein neues Array zurück.
let firstNumbers = [1, 2, 3]; let secondNumbers = [4, 5, 6]; let merged = firstNumbers.concat(secondNumbers); console.log(merged); // [1, 2, 3, 4, 5, 6]
drücken()
Diese Methode fügt Elemente am Ende eines Arrays hinzu und ändert das ursprüngliche Array.
let browsers = ['chrome', 'firefox', 'edge']; browsers.push('safari', 'opera mini'); console.log(browsers); // ["chrome", "firefox", "edge", "safari", "opera mini"]
Pop()
Diese Methode entfernt das letzte Element eines Arrays und gibt es zurück.
let browsers = ['chrome', 'firefox', 'edge']; browsers.pop(); // "edge" console.log(browsers); // ["chrome", "firefox"]
Verschiebung()
Diese Methode entfernt das erste Element eines Arrays und gibt es zurück.
let browsers = ['chrome', 'firefox', 'edge']; browsers.shift(); // "chrome" console.log(browsers); // ["firefox", "edge"]
nicht verschieben ()
Diese Methode fügt dem Anfang eines Arrays ein oder mehrere Elemente hinzu und ändert das ursprüngliche Array.
let browsers = ['chrome', 'firefox', 'edge']; browsers.unshift('safari'); console.log(browsers); // ["safari", "chrome", "firefox", "edge"]
Sie können auch mehrere Elemente gleichzeitig hinzufügenspleißen()
DiesDie Methode ändert ein Array durch Hinzufügen, Entfernen und Einfügen von Elementen.
Die Syntax lautet:
array.splice(index[, deleteCount, element1, ..., elementN])
Index
Hier ist der Ausgangspunkt zum Entfernen von Elementen im ArraydeleteCount
ist die Anzahl der Elemente, die aus diesem Index gelöscht werden sollenelement1, …, elementN
ist das / die hinzuzufügende (n) Element (e)
Elemente entfernen
Nach dem Ausführen von splice () wird das Array mit den entfernten Elementen zurückgegeben und aus dem ursprünglichen Array entfernt.let colors = ['green', 'yellow', 'blue', 'purple']; colors.splice(0, 3); console.log(colors); // ["purple"] // deletes ["green", "yellow", "blue"]
NB : Der deleteCount enthält nicht den letzten Index im Bereich.Wenn der zweite Parameter nicht deklariert ist, wird jedes Element, das mit dem angegebenen Index beginnt, aus dem Array entfernt:
let colors = ['green', 'yellow', 'blue', 'purple']; colors.splice(3); console.log(colors); // ["green", "yellow", "blue"] // deletes ['purple']
Im nächsten Beispiel werden 3 Elemente aus dem Array entfernt und durch weitere Elemente ersetzt:
let schedule = ['I', 'have', 'a', 'meeting', 'tommorrow']; // removes 4 first elements and replace them with another schedule.splice(0, 4, 'we', 'are', 'going', 'to', 'swim'); console.log(schedule); // ["we", "are", "going", "to", "swim", "tommorrow"]
Elemente hinzufügen
Um Elemente hinzuzufügen, müssen wir den Wert deleteCount
auf Null setzen
let schedule = ['I', 'have', 'a', 'meeting', 'with']; // adds 3 new elements to the array schedule.splice(5, 0, 'some', 'clients', 'tommorrow'); console.log(schedule); // ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"]
Scheibe()
Diese Methode ist ähnlich,splice()
aber sehr unterschiedlich. Es werden Subarrays anstelle von Teilzeichenfolgen zurückgegeben.Diese Methode kopiert einen bestimmten Teil eines Arrays und gibt diesen kopierten Teil als neues Array zurück. Das ursprüngliche Array wird nicht geändert.
Die Syntax lautet:
array.slice(start, end)
Hier ist ein einfaches Beispiel:
let numbers = [1, 2, 3, 4] numbers.slice(0, 3) // returns [1, 2, 3] console.log(numbers) // returns the original array
Am besten slice()
weisen Sie es einer neuen Variablen zu.
let message = 'congratulations' const abbrv = message.slice(0, 7) + 's!'; console.log(abbrv) // returns "congrats!"
Teilt()
Diese Methode wird für Zeichenfolgen verwendet . Es unterteilt eine Zeichenfolge in Teilzeichenfolgen und gibt sie als Array zurück.
Here’s the syntax:string.split(separator, limit);
- The
separator
here defines how to split a string either by a comma. - The
limit
determines the number of splits to be carried out
let firstName = 'Bolaji'; // return the string as an array firstName.split() // ["Bolaji"]
another example:
let firstName = 'hello, my name is bolaji, I am a dev.'; firstName.split(',', 2); // ["hello", " my name is bolaji"]
NB: If we declare an empty array, like this firstName.split('');
then each item in the string will be divided as substrings:let firstName = 'Bolaji'; firstName.split('') // ["B", "o", "l", "a", "j", "i"]
indexOf()
This method looks for an item in an array and returns the index where it was found else it returns -1
let fruits = ['apple', 'orange', false, 3] fruits.indexOf('orange'); // returns 1 fruits.indexOf(3); // returns 3 friuts.indexOf(null); // returns -1 (not found)
lastIndexOf()
This method works the same way indexOf() does except that it works from right to left. It returns the last index where the item was found
let fruits = ['apple', 'orange', false, 3, 'apple'] fruits.lastIndexOf('apple'); // returns 4
filter()
This method creates a new array if the items of an array pass a certain condition.
The syntax is:
let results = array.filter(function(item, index, array) { // returns true if the item passes the filter });
Example:
Checks users from Nigeria
const countryCode = ['+234', '+144', '+233', '+234']; const nigerian = countryCode.filter( code => code === '+234'); console.log(nigerian); // ["+234", "+234"]
map()
This method creates a new array by manipulating the values in an array.
Example:
Displays usernames on a page. (Basic friend list display)
const userNames = ['tina', 'danny', 'mark', 'bolaji']; const display = userNames.map(item => { return '' + item + ' '; }) const render = '' + display.join('') + '
'; document.write(render);

another example:
// adds dollar sign to numbers const numbers = [10, 3, 4, 6]; const dollars = numbers.map( number => '$' + number); console.log(dollars); // ['$10', '$3', '$4', '$6'];
reduce()
This method is good for calculating totals.
reduce() is used to calculate a single value based on an array.
let value = array.reduce(function(previousValue, item, index, array) { // ... }, initial);
example:
To loop through an array and sum all numbers in the array up, we can use the for of loop.const numbers = [100, 300, 500, 70]; let sum = 0; for (let n of numbers) { sum += n; } console.log(sum);
Here’s how to do same with reduce()
const numbers = [100, 300, 500, 70]; const sum = numbers.reduce((accummulator, value) => accummulator + value , 0); console.log(sum); // 970
If you omit the initial value, the total will by default start from the first item in the array.const numbers = [100, 300, 500, 70]; const sum = numbers.reduce((accummulator, value) => accummulator + value); console.log(sum); // still returns 970
The snippet below shows how the reduce() method works with all four arguments.
source: MDN Docs

More insights into the reduce() method and various ways of using it can be found here and here.
forEach()
This method is good for iterating through an array.
It applies a function on all items in an array
const colors = ['green', 'yellow', 'blue']; colors.forEach((item, index) => console.log(index, item)); // returns the index and the every item in the array // 0 "green" // 1 "yellow" // 2 "blue"
iteration can be done without passing the index argument
const colors = ['green', 'yellow', 'blue']; colors.forEach((item) => console.log(item)); // returns every item in the array // "green" // "yellow" // "blue"
every()
This method checks if all items in an array pass the specified condition and returntrue
if passed, else false
.
const numbers = [1, -1, 2, 3]; let allPositive = numbers.every((value) => { return value >= 0; }) console.log(allPositive); // would return false
some()
This method checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
checks if at least one number is positiveconst numbers = [1, -1, 2, 3]; let atLeastOnePositive = numbers.some((value) => { return value >= 0; }) console.log(atLeastOnePositive); // would return true
includes()
This method checks if an array contains a certain item. It is similar to .some()
, but instead of looking for a specific condition to pass, it checks if the array contains a specific item.
let users = ['paddy', 'zaddy', 'faddy', 'baddy']; users.includes('baddy'); // returns true
If the item is not found, it returns false
There are more array methods, this is just a few of them. Also, there are tons of other actions that can be performed on arrays, try checking MDN docs herefor deeper insights.
Summary
- toString() converts an array to a string separated by a comma.
- join() combines all array elements into a string.
- concat combines two arrays together or add more items to an array and then return a new array.
- push() adds item(s) to the end of an array and changes the original array.
- pop() removes the last item of an array and returns it
- shift() removes the first item of an array and returns it
- unshift() adds an item(s) to the beginning of an array and changes the original array.
- splice() changes an array, by adding, removing and inserting elements.
- slice() copiesa given part of an array and returns that copied part as a new array. It does not change the original array.
- split() divides a string into substrings and returns them as an array.
- indexOf() looks for an item in an array and returns the index where it was found else it returns
-1
- lastIndexOf() looks for an item from right to left and returns the last index where the item was found.
- filter() creates a new array if the items of an array pass a certain condition.
- map() creates a new array by manipulating the values in an array.
- reduce() calculates a single value based on an array.
- forEach() iterates through an array, it applies a function on all items in an array
- every() checks if all items in an array pass the specified condition and return true if passed, else false.
- some() checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
- includes() checks if an array contains a certain item.
Let’s wrap it here; Arrays are powerful and using methods to manipulate them creates the Algorithms real-world applications use.
Let's do a create a small function, one that converts a post title into a urlSlug.
URL slug is the exact address of a specific page or post on your site.When you write an article on Freecodecamp Newsor any other writing platform, your post title is automatically converted to a slug with white spaces removed, characters turned to lowercase and each word in the title separated by a hyphen.
Here’s a basic function that does that using some of the methods we learnt just now.
const url = '//bolajiayodeji.com/' const urlSlug = (postTitle) => { let postUrl = postTitle.toLowerCase().split(' '); let postSlug = `${url}` + postUrl.join('-'); return postSlug; } let postTitle = 'Introduction to Chrome Lighthouse' console.log(urlSlug(postTitle)); // //bolajiayodeji.com/introduction-to-chrome-lighthouse
in postUrl
, we convert the string to lowercase then we use the split()method to convert the string into substrings and returns it in an array
["introduction", "to", "chrome", "lighthouse"]
in post slug
we join the returned array with a hyphen and then concatenate it to the category string and main url
.
let postSlug = `${url}` + postUrl.join('-'); postUrl.join('-') // introduction-to-chrome-lighthouse
That’s it, pretty simple, right? :)
If you’re just getting started with JavaScript, you should check this repository here, I’m compiling a list of basic JavaScript snippets ranging from
- Arrays
- Control flow
- Functions
- Objects
- Operators
Don’t forget to Star and share! :)
PS: This article was first published on my blog here