Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Array methods are built-in functions that help you work with arrays. Instead of writing loops to add, remove, or search items, you can use these ready-made tools!
Adds one or more elements to the end of an array
const fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits);
// ['apple', 'banana', 'orange']
fruits.push('grape', 'mango');
console.log(fruits);
// ['apple', 'banana', 'orange', 'grape', 'mango']Adds one or more elements to the beginning of an array
const fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits);
// ['apple', 'banana', 'orange']
fruits.unshift('kiwi', 'mango');
console.log(fruits);
// ['kiwi', 'mango', 'apple', 'banana', 'orange']Building a shopping list
Removes the last element and returns it
const fruits = ['apple', 'banana', 'orange']; const removed = fruits.pop(); console.log(removed); // 'orange' console.log(fruits); // ['apple', 'banana'] fruits.pop(); console.log(fruits); // ['apple']
Removes the first element and returns it
const fruits = ['apple', 'banana', 'orange']; const removed = fruits.shift(); console.log(removed); // 'apple' console.log(fruits); // ['banana', 'orange'] fruits.shift(); console.log(fruits); // ['orange']
First in, first out - like a line at a store
Returns the index of the first occurrence, or -1 if not found
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana')); // 1
console.log(fruits.indexOf('grape')); // -1Returns true if element exists, false otherwise
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // falseSee if a user has specific access
Returns a shallow copy of a portion (start to end)
const fruits = ['apple', 'banana', 'orange', 'grape', 'mango']; const some = fruits.slice(1, 3); console.log(some); // ['banana', 'orange'] console.log(fruits); // Original unchanged
Combines two or more arrays into a new array
const fruits = ['apple', 'banana']; const veggies = ['carrot', 'broccoli']; const food = fruits.concat(veggies); console.log(food); // ['apple', 'banana', 'carrot', 'broccoli']
Extracting parts of an array
Joins all elements into a string with a separator
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.join(', ')); // 'apple, banana, orange'
console.log(fruits.join(' - ')); // 'apple - banana - orange'
console.log(fruits.join('')); // 'applebananaorange'Reverses the array in place (modifies original!)
const numbers = [1, 2, 3, 4, 5]; numbers.reverse(); console.log(numbers); // [5, 4, 3, 2, 1]
Combining array methods
map(), filter(), and reduce() that we'll cover in "Array Iteration Methods"!