Tecnate | Last Updated: 2024.04.04 |
Using the power of the superhuman, this document uses the following data to demonstrate common JavaScript array methods:
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
Each codeblock is meant to be a stand-alone example. New information/state from prior examples will not carry over unless explicitly indicated.
Array.length
Identify the number of elements.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
console.log(justiceLeague.length); // 5
Array.includes(searchElement, fromIndex)
Determine if array has a particular element. Returns boolean.
fromIndex
: (optional) index at which to begin search.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
console.log(justiceLeague.includes("Joker")); // false
Array.includes("foo")
- Find an element.String.match("/bar/")
- Match against regex.String.match("baz")
- Find a string.Array.indexOf(searchElement, fromIndex)
Return the index of the first occurrence of an element. Case & whole-word sensitive. Returns -1
if it can’t found.
fromIndex
: (optional) index at which to begin search.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
console.log(justiceLeague.indexOf("supermann")); // -1
console.log(justiceLeague.indexOf("Flash")); // 3
Array.every(callbackFn, thisArg)
Test whether ALL elements in an array pass the conditions of the callback function. Returns a boolean.
callbackFn
: a function to execute for each element, called with the following arguments:
(element, index, Array)
thisArg
: (optional) value to use asthis
during execution.
const ages = [28, 33, 30, 19];
const allAdults = ages.every((age) => age >= 18);
const allOver30 = ages.every(function (age) {
return age > 30;
});
console.log(allAdults); // true
console.log(allOver30); // false
Array.push(item1, item2, ...itemN)
Add one or more elements to the end of an array.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
justiceLeague.push("Aquaman", "Shazam");
console.log(justiceLeague); // [ 'Superman','Batman','Wonder Woman','Flash','Green Lantern','Aquaman','Shazam' ]
Array.pop()
Remove a single element from the end of an array.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
justiceLeague.pop();
console.log(justiceLeague); // [ 'Superman', 'Batman', 'Wonder Woman', 'Flash', ]
Array.unshift(item1, item2, ...itemN)
Add one or more elements to the beginning of an array.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
justiceLeague.unshift("Shazam");
console.log(justiceLeague); // [ 'Shazam', 'Superman', 'Batman', 'Wonder Woman', 'Flash', 'Green Lantern' ]
Array.shift()
Remove a single element at the beginning of an array.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
justiceLeague.shift();
console.log(justiceLeague); // [ 'Batman', 'Wonder Woman', 'Flash', 'Green Lantern' ]
Mutate
Array.splice(startIndex, deleteCount, addItem1, ...addItemN)
Remove, add, or replace elements in an array.
NOTE: This method changes the original array and may change the value of this
.
startIndex
: zero-based index at which to begin changing array.deleteCount
: (optional) integer indicating number of elements to remove.addItem
: (optional) elements to add to the array, beginning fromstartIndex
.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
justiceLeague.splice(2, 3);
console.log(justiceLeague); // [ 'Superman', 'Batman' ]
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
justiceLeague.splice(1, 0, "Shazam", "Aquaman");
console.log(justiceLeague); // [ 'Superman','Shazam','Aquaman','Batman','Wonder Woman','Flash','Green Lantern' ]
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
const sidekicks = ["Robin", "Superboy"];
justiceLeague.splice(2, 2, ...sidekicks);
console.log(justiceLeague); // [ 'Superman', 'Batman', 'Robin', 'Superboy', 'Green Lantern' ]
Shallow Copy
Array.slice(startIndex, stopIndex)
String.slice(start, end)
Copy any portion an array or string and use those copied elements to create a new array.
NOTE: The original array remains unchanged.
startIndex
: (optional) inclusive.stopIndex
: (optional) exclusive.- Negative values count back from the end of the array:
startIndex + Array.length
orstopIndex + Array.length
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
const teamAlpha = justiceLeague.slice(0, 3);
console.log(teamAlpha); // [ 'Superman', 'Batman', 'Wonder Woman' ]
let password = "OpenSesame";
let cipher = password.slice(0, 5);
console.log(cipher); // OpenS
Array1.concat(Array2).concat(...ArrayN)
Concatenate two or more arrays.
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
const sidekicks = ["Robin", "Superboy"];
const heroes = justiceLeague.concat(sidekicks);
console.log(heroes); // [ 'Superman','Batman','Wonder Woman','Flash','Green Lantern','Robin','Superboy' ]
const teamA = ["Huntress", "Black Canary"];
const teamB = ["Red Tornado", "Aquaman"];
const teamAB = [...teamA, ...teamB];
console.log(teamAB); // [ 'Huntress', 'Black Canary', 'Red Tornado', 'Aquaman' ]
Math
object.const ages = [28, 33, 30, 19];
console.log(Math.min(ages)); // NaN
console.log(Math.min(...ages)); // 19
Shallow Copy
Array.filter(callbackFn, thisArg)
const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
const firstAndLast = justiceLeague.filter(function (item, index) {
return index < 1 || index > justiceLeague.length - 2;
});
console.log(firstAndLast); // [ 'Superman', 'Green Lantern' ]
const sidekicks = ["Robin", "Superboy", "Kid Flash", "Aqualad"];
const longNames = sidekicks.filter((name, index) => name.length > 7);
console.log(longNames); // [ 'Superboy', 'Kid Flash' ]
.filter()
& .includes()
.const justiceLeague = ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern"];
const filterMan = justiceLeague.filter(function (name) {
return name.includes("man");
});
console.log(filterMan); // ["Superman", "Batman", "Wonder Woman"];
const sidekicks = ["Robin", "Superboy", "Kid Flash", "Aqualad"];
const filterEvens = sidekicks.filter((name, index) => {
return index % 2 !== 0;
});
console.log(filterEvens); // [ 'Superboy', 'Aqualad' ]
Iterate
Array.map(callbackFn, thisArg)
Array.map(function(ArrayValue, index){})
Array.map((ArrayValue, index) => {})
Return a new array with all original elements modified by a callback function.
const ages = [28, 33, 30, 19];
const doubleAges = ages.map(function (age) {
return `${age * 2}`;
});
console.log(doubleAges); //[ '56', '66', '60', '38' ]
const sidekicks = ["Robin", "Superboy"];
const cities = ["Gotham", "Metropolis"];
const jurisdiction = sidekicks.map((name, index) => {
const city = cities[index];
return `${name}: ${city}`;
});
console.log(jurisdiction); // [ 'Robin: Gotham', 'Superboy: Metropolis' ]
Array.split(separator, limit)
Split a string and return substrings as elements in an array.
separator
: can beundefined
, a string, orSymbol.split
object (e.g regex).limit
: (optional) non-negative number of elements to be included.
const alterEgos = "Bruce Wayne, Clark Kent";
const secretIdentities = alterEgos.split(",");
console.log(secretIdentities); // [ 'Bruce Wayne', ' Clark Kent' ]
Array.join(separator)
Join array elements into a string. If you leave the separator empty, the string will be joined by commas.
const secretIdentities = ["Bruce Wayne", " Clark Kent"];
const alterEgos = secretIdentities.join(",");
console.log(alterEgos); // Bruce Wayne, Clark Kent
Object.entries(exampleObject)
Return an object as an array of [key, value] pairs
const jurisdiction = {
Superman: "Metropolis",
Batman: "Gotham",
Flash: "Central City",
};
console.log(Object.entries(jurisdiction));
/*[
[ 'Superman', 'Metropolis' ],
[ 'Batman', 'Gotham' ],
[ 'Flash', 'Central City' ]
]*/
Object.entries(jurisdiction).forEach(([key, value]) => console.log(`${key}: ${value}`));
// 'Superman: Metropolis'
// 'Batman: Gotham'
// 'Flash: Central City'