.slice
Works the same as for strings. Specify start from and start to in parameters. CAN ALSO BE USED to return a shallow copy of array.
let arr = ['a', 'b', 'c', 'd', 'e'];
//SLICE
arr.slice(2); // Returns c, d, e
arr.slice(2,4); // Returns c, d
arr.slice(-2); // Slices from rear (returns last two) d e
arr.slice(-1); // Returns last (e)
arr.slice(1, -2); // returns b, c
arr.slice; creates shallow copy of orignal array (same as [...arr]
.splice()
Same as above but MUTATES the original array (returns mutated array)
.toSpliced()
Non-destructive method of the above
.reverse()
Reverses the original array (mutates).
.toReversed()
Non-destructive method of reverse.
.concat(array)
Concatonated two arrays (as […arr, arr]). Doesn’t mutate original arrays.
.join(‘-‘)
Turns the array into a string joined by optional parameter
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.join('+'); // Returns string of a+b+c+d+e
.at() (ES6)
Works just the same as [] however can use negative index (also works on strings):
// Get last array element.
arr.at(-1); works the same as arr[arr.length - 1]
forEach
Used for looping through arrays. Requires a callback function.
Passes the element, index and entire array
arr.forEach(function (element, index, array) {
// Do something
});
YOU CANNOT BREAK OUT OF THE forEach LOOP. Use For of instead.
Works also with Maps and Sets. (will not return key of sets because there isn’t one).
.map()
Map loops through array and applies a function and builds a brand new array (no side effects).
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
const eurToUsd = 1.1;
const movementsUSD = movements.map( function(mov) {
return mov * eurToUsd;
}) // Functional programming
//Arrow function version.
const movementsUSD = movements.map(mov => mov * eurToUsd);
// EXAMPLE 2
const movementsDescriptions = movements.map((mov,i ) => {
`Movement ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdrew'} ${Math.abs(mov)}`
});
// EXAMPLE 3
const user = 'Steven Thomas Williams';
const username = user
.toLowerCase()
.split(' ')
.map(word => word[0])
.join('');
console.log(username); // returns 'stw'
.filter(condition)
Will go through and return a new array containing all elements in original array the meet the specified test condition.
const deposits = movements.filter(function(mov){
return mov > 0;
}); creates a new array with only deposits
const withdrawals = movements.filter(mov => mov < 0); // returns new array with only negative values.
.reduce(condition)
Boils all array elemements down to one single value (like adding all elements together.
// accumalator -> SNOWBALL
const balance = movements.reduce(function (acc, cur, i, arr) {
return acc + cur;
}, 0); // 0 defines the start value of the accumalator
console.log(balance);
// simplified arrow function:
const balance = movements.reduce((acc,cur) => acc + cur, 0);
// Maximum values
const maxValue = movements.reduce((acc, mov) => acc > mov ? acc : mov, movements[0]); // Returns the highest amount in the array
.find(condition) ES6
Needs a callback function that returns a boolean. It will loop until the first true value is returned and will return the first element only.
const account = accounts.find(acc => acc.owner === 'Jessica Davis'); // returns the first object that returns a true value.
.findIndex(condition) ES6
Needs a callback function that returns a boolean. It will loop until the first true value is returned and will return the first element index only.
.findLast(condition) & .findLastIndex(condition) ES2023
Same as above but returns last value / index.
.some(boolean condition)
Similar to includes but includes a condition instead rather than a specific value
.every(boolean condition)
Method returns true if every element in array meets the condition.
array.flat(depth)
No callback required, flattens the array.
array.flatMap(callback)
No callback required, Creates a map and then flattens the array.
Sorting Arrays
Sorting Arrays
arr.sort() // sorts in alphabeltical (converts to strings) - MUTATES original
// To sort in numerical strings ascending order (loops through array)
// return < 0, A, B (keep order)
// return > 0, B, A (switch order)
arr.sort((a, b) => {
if (a > b) return 1;
if (b > a) return -1;
}); //
// For numbers. simplified
arr.sort(( a,b ) => a - b);
// Non destructive method
const newArray = arr.toSorted(( a,b ) => a - b);
Array Grouping (Object.groupBy)
Creates an Object grouping elements as per callback condition.
const groupedArr = Object.groupBy(arr, callback => callback > 0 ? 'positives' : 'negatives') //
Generating arrays programatically
const arr = new Array(7) // creates 7 empty slots
arr.fill(1) // fills the array with 1s
arr.fill(1, 3) // starts from index 3 [ , , 1, 1, 1, 1]
arr.fill(1, 3, 5) // fills from index 3 until index 5
const arr = Array.from({length: 7), () => 1); // creates array full of 1s
const inc = Array.from({length: 7}, (cur, i) => i + 1); // creates incrementing array
// Create an array of 100 random dice rolls
const diceRolls = Array.from(
{ length: 100 },
() => Math.floor(Math.random() * 6) + 1
);
console.log(diceRolls);
.with(i, val)
Creates a new array copy but replaces the element at index i with new value
When to use each method?
To mutate original
Add to original
- push (end)
- unshift (start)
Remove from original
- pop (end)
- shift (start)
- splice (any)
Others:
A new array based on original
Same length as original
- map (loop)
- filter (using condition)
- slice (taking portion)
- with (with one item replaced)
- flat (flattened)
- flatMap (flattened into a map)
- toReversed
- toSorted
- toSpliced (with deleted items)
- concat (joining two arrays)
An array index
- indexOf (based on value)
- findIndex / findLastIndex (based on test condition)
An array index
I want to know ifd array includes…
- includes (based on value)
- some (based on test condtion (boolean)
- every (based on test condtion (boolean)
I want a new string
- join (based on seperator)
To transform to value
- reduce (based on accumulator – boils down array to a single value)
to just loop over the array
- forEach (does not create a new array, just loops over it)
Other useful tools
- Object.groupBy – Grouping an array by categories
- Array.from – Creating a new array from scratch
- new Array(n) – create a new array from scractch with n empty positions (use with .fill method)
- […arr1, …arr2] joining arrays
- [… new Set(arr)] Creating a new array containing unique values from arr
- [… new Set(arr1).intersection(new Set(arr2))] – Create a new array containing unique elements that are present in both arr1 and arr2.