Cookie Consent by Free Privacy Policy Generator 📌 Summary of Common Javascript Array Methods

🏠 Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeiträge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden Überblick über die wichtigsten Aspekte der IT-Sicherheit in einer sich ständig verändernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch übersetzen, erst Englisch auswählen dann wieder Deutsch!

Google Android Playstore Download Button für Team IT Security



📚 Summary of Common Javascript Array Methods


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

Here's a summary on common JavaScript Array methods:

List of common JavaScript Array Methods

1) length

Return the length / size of an array

const pets = ['cat', 'dog'];
console.log(pets.length);  // Output: 2

2) push() & pop()

push(): Adds one or more elements to the end of an array

const pets = ['cat', 'dog'];
pets.push('hamster');
console.log(pets);   // Output: ['cat', 'dog', 'hamster']

pets.push('bunny', 'parrot');
console.log(pets);  
// Output: ['cat', 'dog', 'hamster', 'bunny', 'parrot']

pop(): Removes the last element from an array and returns that element

const pets = ['cat', 'dog', 'hamster'];
const lastElement = pets.pop();

console.log(lastElement);   // Output: 'hamster'
console.log(pets);   // Output: ['cat', "dog']

3) shift() & unshift()

shift(): Removes the first element from an array and returns that element

const pets = ['cat', 'dog', 'hamster'];
const firstElement = pets.shift();

console.log(firstElement);  // Output: 'cat'
console.log(pets);  // Output: ['dog', 'hamster']

unshift(): Adds one or more elements to the beginning of an array & return a new length of an array

const pets = ['cat', 'dog'];
pets.unshift('bunny', 'lizard');
console.log(pets);   
// Output: ['bunny', 'lizard', 'cat', 'dog']

let newArrayLength = pets.unshift('parrot');
console.log(pets);   
// Output: ['parrot', 'bunny', 'lizard', 'cat', 'dog']
console.log(newArrayLength);   // Output: 5

4) slice() & splice()

slice(): Returns a shallow copy of a portion of an array selected from start index to end index (end index item not included), without modifying the original array

slice(startIndex, endIndex):

const pets = ['cat', 'dog', 'hamster', 'bunny', 'lizard'];
let result1 = pets.slice(2);
console.log(result1);  
// Output: ['hamster', 'bunny', 'lizard']

let result2 = pets.slice(2, 4);
console.log(result2);   
// Output: ['hamster', 'bunny']

let result3 = pets.slice(-3);
console.log(result3);   
// Output: ['hamster', bunny', 'lizard']

let result4 = pets.slice();
console.log(result4);   
// Output: ['cat', 'dog', 'hamster', 'bunny', 'lizard']

splice(): Changes the contents of an array by removing, replacing, or adding elements. It modifies the original array

splice(index, deleteCount, item):

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');   // insert at index 1
console.log(months);   
// Output: ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');   // replace 1 element at index 4
console.log(months);   
// Output: ['Jan', 'Feb', 'March', 'April', 'May']

5) join()

Joins all elements of an array into a string

const elements = ['heat', 'oxygen', 'fuel'];
console.log(elements.join()); // Output: "heat,oxygen,fuel"

6) .concat() or ... Spread Operator

.concat() or ...: Combine arrays together into one array

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr1 = arr1.concat(arr2);
console.log(combinedArr1);
// Output: [1,2,3,4,5,6]

const combinedArr2 = [...arr1, ...arr2];  // more flexible
console.log(combinedArr2);
// Output: [1,2,3,4,5,6]

6) indexOf() & includes()

indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it's not present

const pokemons = ['pikachu', 'squirtle', 'bulbasaur'];
console.log(pokemons.indexOf('squirtle'));   // Output: 1
console.log(pokemons.indexOf('charmander'));   // Output: -1

includes(): Determines whether an array includes a certain element, returning true or false as appropriate

const myWeekendPlan = ['sleep', 'video games', 'anime', 'unhealthy food'];
console.log(myWeekendPlan.includes('anime'));   // Output: true
console.log(myWeekendPlan.includes('work'));   // Output: false

7) forEach()

Executes a provided function once for each array element

const array1 = ['hehe', 'haha', 'hoho'];
array1.forEach((element) => console.log(element));

Output:
'hehe'
'haha'
'hoho'

8) filter()

Creates a new array with all elements that pass the test provided by a provided function

const words = ['good', 'nice', 'great', 'amazing', 'cool', 'awesome'];
const result = words.filter((word) => word.length > 6);
console.log(result);   // Output: ['amazing', 'awesome']

9) map()

Creates a new array by calling a provided function on each element of the original array

const array1 = [1, 2, 3, 4];
const map1 = array1.map((x) => x * x);
console.log(map1);   // Output: [1, 4, 9, 16]

const cart = [5, 15, 25];
const cartWithTax = cart.map((cost) => cost * 1.2);
console.log(cartWithTax);   // Output: [6, 18, 30]

10) reduce()

Applies a function to reduce the array to a single value (from left-to-right)

const cart = [5, 15, 25];
const cartTotal = cart.reduce((total, itemPrice) => total + itemPrice, 0);  // 0 = initial value of total
console.log(cartTotal);   // Output: 45

11) sort()

Sorts the elements of an array in place and returns the sorted array

If comparison function is not provided, sort converts elements to strings & sorts them based on their UTF-16 code units (may not fit in most use case, so we usually use it with a comparison function)

const months = ['March', 'Jan', 'Feb', 'Dec'];
console.log(months.sort());   
// Output: ['Dec', 'Feb', 'Jan', 'March']

const numbers = [30, 11, 110, 5, 20, 41];
console.log(numbers.sort());
// Output: [11, 110, 20, 30, 41, 5]  <- doesn't get sorted by numeric value

When comparison function is provided & it returns a negative number, it indicates the first element should come before the second element. If it returns a positive number, it indicates that the first element should come after the second element in the sorted order. If it returns 0, the elements are considered as equal & their order remains unchanged

const numbers = [3, 1, 5, 2, 4];
numbers.sort((a, b) => a - b);  // from small to large
console.log(numbers);   
// Output: [1, 2, 3, 4, 5]

const names = ['alan', 'may', 'alice', 'ben', 'john' , 'catie'];
names.sort((a, b) => a.localeCompare(b));  // sort names alphabetically
console.log(names);   
// Output: ["alan", "alice", "ben", "catie", "john", "may"]

12) find() & findIndex()

find(): Returns the first element in the array that satisfies the provided function

const numbersArray = [3, 99, 108, 87, 65, 110];
const foundNumber = numbersArray.find((element) => element > 100);
console.log(foundNumber);    // Output: 108

findIndex(): Returns the index of the first element in the array that satisfies the provided function

const numbersArray = [10, 20, 30, 40, 50];
const foundIndex = numbersArray.findIndex((number) => number > 25);
console.log(foundIndex);    // Output: 2

13) some()

Check if at least one element in an array satisfies a specified condition, returns true if any element passes the condition

const products = [
  { name: 'Smartphone', price: 500 },
  { name: 'Laptop', price: 1000 },
  { name: 'Microphone', price: 30 },
  { name: 'Headset', price: 50 },
];
const priceMaxLimit = 100;
const hasItemsInPriceRange = products.some(product => product.price <= priceMaxLimit);
console.log(hasItemsInPriceRange);  // Output: true

14) every()

Check if all elements in an array satisfy a specified condition, returns true only if all elements pass the condition.

const surveyQuestions = [
  { question: 'Question 1', answer: 'Yes' },
  { question: 'Question 2', answer: 'No' },
  { question: 'Question 3', answer: '' },    // unanswered
];
const isSurveyComplete = surveyQuestions.every(question => question.answer);   
console.log(isSurveyComplete)   // Output: false

That's all and hope that it helps! I always find myself googling some methods again & again so decided to write this & help me memorize it better lol

Reference: Mozilla's web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

...



📌 Summary of Common Javascript Array Methods


📈 55.49 Punkte

📌 Learn the JavaScript Array.every() and Array.some() methods


📈 43.45 Punkte

📌 JavaScript Array Tutorial – Array Methods in JS


📈 43.45 Punkte

📌 Convert Array of Starings to Array of Numbers in JavaScript


📈 31.82 Punkte

📌 JavaScript Sort Array - How to Sort an Array Accurately


📈 31.82 Punkte

📌 JS Sum of an Array – How to Add the Numbers in a JavaScript Array


📈 31.82 Punkte

📌 JavaScript Array Length – How to Find the Length of an Array in JS


📈 31.82 Punkte

📌 The Javascript higher order array methods with reactjs examples


📈 31.24 Punkte

📌 20 JavaScript: Array Methods


📈 31.24 Punkte

📌 JavaScript Array Methods: Understand By Implementing


📈 31.24 Punkte

📌 JavaScript Array Methods Cheatsheet


📈 31.24 Punkte

📌 filter vs. find: JavaScript Array Methods


📈 31.24 Punkte

📌 17 JavaScript Array Methods Everyone Needs to Know


📈 31.24 Punkte

📌 All the new javascript array methods you missed in 2023


📈 31.24 Punkte

📌 JavaScript Array Methods: Map vs Filter vs Redux


📈 31.24 Punkte

📌 10 JavaScript Array Methods That Will Make You Look Like a Pro


📈 31.24 Punkte

📌 JavaScript Array Methods: Understanding `flatMap`


📈 31.24 Punkte

📌 15 Must-Know Javascript array methods


📈 31.24 Punkte

📌 JavaScript Array Methods: A Comprehensive Guide


📈 31.24 Punkte

📌 Lesser know JavaScript array methods part -1


📈 31.24 Punkte

📌 JavaScript, useState React Array Handling methods.


📈 31.24 Punkte

📌 Unleashing the Power of Customized Array Methods in JavaScript.


📈 31.24 Punkte

📌 13 Most Common JavaScript String Methods You Should Know About


📈 28.65 Punkte

📌 JavaScript console methods for better debugging - 🔮 Unlocking JavaScript Magic


📈 26.44 Punkte

📌 [dos] Microsoft Edge Chakra JIT - 'Array.prototype.reverse' Array Type Confusion


📈 24.41 Punkte

📌 #0daytoday #Microsoft Edge Chakra JIT - Array.prototype.reverse Array Type Confusion Exploit [#0day #Exploit]


📈 24.41 Punkte

📌 Microsoft Edge Chakra JIT Array.prototype.reverse Array Type Confusion


📈 24.41 Punkte

📌 Microsoft Edge Chakra JIT Array.prototype.reverse Array Type Confusion


📈 24.41 Punkte

📌 FFmpeg Array Access MXF File Out-of-Array memory corruption


📈 24.41 Punkte

📌 Bash For Loop Array: Iterate Through Array Values


📈 24.41 Punkte

📌 Print the sum of array after doing k queries on the array


📈 24.41 Punkte

📌 How to pass array in another array of objects?


📈 24.41 Punkte

📌 Maximize Array sum by adding multiple of another Array element in given ranges


📈 24.41 Punkte

📌 Convert 1d Array to 2d Array Python


📈 24.41 Punkte

📌 How to Create an Array in Java – Array Declaration Example


📈 24.41 Punkte











matomo