Arrays
Top array methods, ranked from most to least used.
map()
Same map
as OCAML. Modifies each element on the array based on a function passed and returns a new Array.
The map()
takes one argument:
λ
callback function (or lambda) that accepts arguments:e
- element to be modifiedidx
[optional]arr
[optional]
Good to know:
- Returns a
new Array
const newarr = [1, 2, 3, 4].map((e, idx, arr) => elem * 2)
// newArr -> [2,4,6,8]
filter()
Filters out elements based on a condition.
The filter()
function takes one argument:
-
λ
- callback function (or lambda), which is executed for each element in the array:e
- current element from array being processed.idx
[optional]arr
[optional]
Callback must return
True
orFalse
for each element.
Only elements that returnTrue
are kept in the new array.
Return value:
new
array with the filtered elements
Good to know:
filter()
is an immutable function (returns a new array).
const evenNumbers = [1, 2, 3, 4, 5, 6].filter( (number) =>
number % 2 === 0;
);
evenNumbers // -> [2, 4, 6]
concat()
Joins two arrays into single one.
Good to know:
concat()
is an immutable function (returns a new array).
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
array3 // -> ['a', 'b' ,'c', d', 'e', 'f']
Caution
In other programming languages [1,2] + [3] = [1,2,3]
works but not in Javascript.
join()
Join each element of the array with the passed value.
Return value: string
const arr = [1, 2, 3, 4]
const arrToString = arr.join("-")
arrToString // -> "1-2-3-4"
slice()
Selects a subarray from the array.
arr.slice(start,end)
Selects the elements from start
to end
(end
excluded) and returns a new Array
.
If only start
is given, from start
index select current item to the end of the array.
Good to know:
slice()
is an immutable function, shallow copy.
const nums = [0, 1, 2, 3, 4];
const test1 = nums.slice(2);
test1 // -> [2, 3, 4]
const test2 = nums.slice(0, 2);
test2 // -> [0, 1]
splice()
Removes and replace elements in the array.
arr.splice(start)
arr.splice(start, deleteCount)
arr.splice(start, deleteCount, item1)
arr.splice(start, deleteCount, item1, item2, ..., itemN)
At index start
delete deleteCount
items and insert item1
, ... itemN
.
If only start
is given, from start
index delete current item to the end of the array.
Warning
splice()
is an in-place function.
const nums = [0,1,2,3,4]
const alphabet = ['a', 'b', 'c']
nums.splice(4, 1, 'new');
nums // -> [0,1,2,3,'new']
alphabet.splice(1)
alphabet // -> ['a']
reduce()
Iterates each element of the array, applies a callback function to each element and accumulates a single result.
Same as fold_left
in OCAML. reduce()
accepts 2 arguments:
λ
- callback function (or lambda) with 4 parameters:
acc
- accumulator at each iteration.e
- current element from array being processed.idx
- index of the element being processed [optional]arr
- current array [optional]
The return
updates the accumulator for the next iteration
The return
must be same type as initial_acc
initial_acc
- an initial value for theacc
. If not given,acc = A[0]
and loop starts atA[1]
Return value:
- a new accumulated result after iterating the array.
Warning
- Callback function must
return
the newacc
, needed for the next iteration.
const sum = [1, 2, 3, 4, 5].reduce((acc, e) => {
// acc = acc + e
return acc + e
}, 0)
// sum -> 15
every()
Checks if all elements in an array passes a given test function
The every()
takes one argument:
λ
- callback function (or lambda) accepts arguments:e
- element to be testedidx
[optional]arr
[optional]
Return value:
True
if ALL passes otherwise,False
(search stops)
/* Check for odd in array */
[2, 6, 8, 1, 4].every((e) => e % 2 == 1)
// Loop1, e -> 2, False, ❌ end loop,
// -> False
[1, 3, 5, 7].every((e) => e % 2 == 1)
// Loop1, e -> 1, True
// Loop2, e -> 3, True
// Loop3, e -> 5, True
// Loop4, e -> 7, True, ✅ end loop
// -> True
some()
Checks if at least one element in an array passes a given test function
The some()
function takes one argument:
λ
compare function (or lambda), that gives a condition to be mete
- element to be testedidx
[optional]arr
[optional]
Return value:
- Returns
True
if at least ONEe
passes (search stops) otherwiseFalse
// Check for odd in array
[2, 6, 8, 1, 4].some((elem) => elem % 2 == 1)
// Loop1, e -> 2, False
// Loop2, e -> 6, False
// Loop3, e -> 8, False
// Loop4, e -> 1, True, ✅ end loop
// Loop5, never runs
// -> True
sort()
Sorts an array in ascending or descending order. By default ascending.
Warning
sort()
is in-place (modifies the array).
const fruits = ["banana", "apple", "orange", "grape"]
fruits.sort()
fruits // -> ['apple', 'banana', 'grape', 'orange']
The sort()
function takes one argument:
- A compare function (or lambda) that compares 2 elements at a time
a
- first elementb
- second element- If
compareFunction(a, b)
returns-1
, NO SWAP - If
compareFunction(a, b)
returns1
, SWAPS ->[b,a]
- If
compareFunction(a, b)
returns0
, NO SWAP
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort(compareFunction(a, b) {
if (a > b) {
return -1; // NO SWAP
} else if (a < b) {
return 1; // SWAP
} else {
return 0; // NO SWAP
}
});
// fruits -> ['orange', 'grape', 'banana', 'apple']
flat()
Takes an array and recursively reduces nested arrays to a specific depth
. By default, depth = 1
(one level deep)
arr.flat()
arr.flat(depth)
arr.flat(Infinity)
Good to know:
flat()
returns a new array.
const arr = [0, 1, [2, [3, [4, 5]]]];
arr.flat(); // -> [0, 1, 2, [3, [4, 5]]]
arr.flat(2); // -> [0, 1, 2, 3, [4, 5]]
arr.flat(Infinity); // -> [0, 1, 2, 3, 4, 5]
flatMap()
A combination of map()
and flat()
Good to know:
flatMap()
returns a new array.
const arr1 = [1, 2, 1];
const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));
result; // -> [1, 2, 2, 1]
for of
Assume we have an array called sums
.
Good to know:
of
iterates the elements of an iterable (Array, string, ...)- while
in
iterates the key of an object
for (let each of nums) {
...
}
The only way to get the index
using for of
loop.
for (let [index,each] of nums.entries()) {
...
}
The conventional for loop.
for (let i = 0; i < nums.length; i++) {
// i <- current index
// nums[i] <- current element
}
forEach()
Allows to execute a function on each element of the array.
The forEach
function takes one argument:
- a callback function (or lambda) that do something to each element, and accepts destructuring:
element
index
array
const numbers = [1, 2, 3, 4, 5];
numbers.forEach( (element) => {
...
});
// [2, 3, 4, 5, 6]
numbers.forEach( (elem, idx, arr) =>
...
)
find()
Find the first occurrence in the array after given function condition returns true.
Returns: the first element
found
fruits = ["apple", "pear", "banana", "orange", "plum", "grape"]
fruit = fruits.find((elem) => elem.length >= 6)
fruit // -> banana
findIndex()
Same as find()
, but returns the first index
found.
fruits = ["apple", "pear", "banana", "orange", "plum", "grape"]
fruit_idx = fruits.find((elem) => elem.length >= 6)
fruit_idx // -> 2
indexOf()
Find in the array the item given and returns its index.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
beasts.indexOf('bison') // -> 1
structureClone()
Creates a deep copy of a structure of type Object
:
- Array
- ArrayBuffer
- Object
- Date
- rest data primitives.
structuredClone(value)
structuredClone(value, options)
Useful for frameworks like in react, to construct a new reference of an object.
Other workarounds (not recommended):
// 1.
[...array]
// 2.
obj !== {...obj} // but both references to the same obj.arr
// 3.
JSON.parse(JSON.stringify(arr)) // non-compatible with Set() or Date() and others
// could take huge memory for large data