JavaScript Array Method Playground
by Keith Rowles • 20/10/2023JavaScript
Summary
Playing around with javascript array methods (join, pop, push +) and iteration (map, filter, reduce +) plus more.
Array to String
The JavaScript method toString() converts an array to a string of (comma separated) array values.
const fruitsArray = ['Banana', 'Orange', 'Apple', 'Mango'];
// to string
document.getElementById('demo').innerHTML = fruitsArray.toString();
Banana,Orange,Apple,Mango
Join
The join() method also joins all array elements into a string.
// join
document.getElementById('app').innerHTML = fruitsArray.join('-');
Banana-Orange-Apple-Mango
Pop
The pop() method removes the last element from an array
The pop() method returns the value that was “popped out”:
let fruit = fruits.pop();
New Array: Watermelon,Blue Berry,Strawberry
Popped Item: Rasberry
Push
The push() method adds a new element to an array (at the end):
The push() method returns the new array length:
let nameArray = ['keith', 'bob', 'sally', 'mary', 'jane', 'sue'];
nameArray.push('john');
New Array:
keith,bob,sally,mary,jane,sue,john
There is also shift and unshift
Concat
The concat() method merges (concatenates) arrays: The concat() method does not change the existing arrays. It always returns a new array.
const myGirls = ['Cecilie', 'Lone'];
const myBoys = ['Emil', 'Tobias', 'Linus'];
const myKids = ['Bob', 'Mary', 'Toby'];
const myChildren = myGirls.concat(myBoys, myKids);
Cecilie,Lone,Emil,Tobias,Linus,Bob,Mary,Toby
Splice
The splice() method adds new items to an array.
const vegetables = ['cabbage', 'corn', 'beans', 'pumpkin'];
vegetables.splice(2, 0, 'potatoe', 'tomato');
New Array:
cabbage,corn,potatoe,tomato,beans,pumpkin
Slice
The slice() method slices out a piece of an array into a new array.
const nuts = ['brazil', 'peanuts', 'peacans', 'hazelnuts', 'walnuts'];
const nut = nuts.slice(4);
Sliced:
walnuts
Iteration
forEach()
The forEach() method calls a function (a callback function) once for each array element.
const numberArray = [1, 2, 34, 58, 987, 3, 45, 2, 66];
let txt = '';
// callback function
numberArray.forEach(myFunction);
function myFunction(value) {
txt += value + '<br>';
}
1
2
34
58
987
3
45
2
66
const dinner = [
'meat pie',
'spagetti',
'marinara',
'baked beans',
'sausage roll',
];
let mydinner = '';
// inline function
dinner.forEach((item, index) => {
mydinner += `${item} is at index ${index}` + '<br>';
});
meat pie is at index 0
spagetti is at index 1
marinara is at index 2
baked beans is at index 3
sausage roll is at index 4
const numberArray2 = [122, 233, 34, 581, 987, 38, 45, 29, 166];
let numX = '';
// arrow function
numberArray2.forEach((value) => {
numX += value + '<br>';
});
122
233
34
581
987
38
45
29
166
const fastfooditems = [
{ id: '🍔', name: 'Super Burger', price: 399 },
{ id: '🍟', name: 'Jumbo Fries', price: 199 },
{ id: '🥤', name: 'Big Slurp', price: 299 },
];
fastfooditems.forEach((item) => {
burgerBox.innerHTML += `
<li>
${item.id} ${item.name} - ${(item.price / 100).toFixed(2)}
</li>
`;
});
for (let i = 0; i < fastfooditems.length; i++) {
const item = fastfooditems[i];
friesBox.innerHTML += `
<li>
${item.id} ${item.name} - ${(item.price / 100).toFixed(2)}
</li>
`;
}
map()
The map() method creates a new array by performing a function on each array element.
The map() method does not execute the function for array elements without values.
The map() method does not change the original array.
let rings = ['Bilbo', 'Gandalf', 'Nazgul'];
const ringList = rings.map((item) => item.length);
5,7,6
const newNums = [45, 4, 9, 16, 25];
const multipyResults = newNums.map(multiplyByTwo);
function multiplyByTwo(value) {
return value * 2;
}
90,8,18,32,50
const halfOffFries = fastfooditems.map((item) => {
if (item.id === '🍟') {
return {
...item,
price: item.price / 2,
};
}
return item;
});
document.getElementById('halfFries').innerHTML =
halfOffFries[1].id + ' ' + halfOffFries[1].name + ' ' + halfOffFries[1].price;
🍟 Jumbo Fries 99.5
filter()
The filter() method creates a new array with array elements that passes a test.
const over18 = newNums.filter(myFilterFunction);
function myFilterFunction(value) {
return value > 18;
}
document.getElementById('filterBox').innerHTML = over18;
45,25
const expensiveItems = fastfooditems.filter((item) => item.price > 199);
const expensiveFilterBox = document.querySelector('#filterBox2');
expensiveItems.forEach((item) => {
expensiveFilterBox.innerHTML += `
<li>
${item.id} ${item.name} - ${(item.price / 100).toFixed(2)}
</li>
`;
});
🍔 Super Burger - 3.99
🥤 Big Slurp - 2.99
reduce()
The reduce() method runs a function on each array element to produce (reduce it to) a single value.
const bigNumbers = [45, 4, 9, 16, 25];
let bigSum = bigNumbers.reduce(reduceBigNumbers);
let bigSum2 = bigNumbers.reduce(reduceBigNumbers, 100);
function reduceBigNumbers(total, value) {
return total + value;
}
The sum is 99
The sum is 199
every()
The every() method check if all array values pass a test.
const ages = [45, 4, 9, 16, 25];
let allOver18 = ages.every(ageCheck);
function ageCheck(value) {
return value > 18;
}
false
some()
The some() method check if some array values pass a test.
let someOver18 = ages.some(ageCheck);
true
indexOf()
The indexOf() method searches an array for an element value and returns its position.
const fruityFruity = ['Apple', 'Orange', 'Apple', 'Mango', 'Melon', 'Pear'];
let fruitPosition = fruityFruity.indexOf('Apple');
0
find()
The find() method returns the value of the first array element that passes a test function.
const firstNumbers = [4, 9, 16, 25, 29];
let firstFind = firstNumbers.find(ageCheck);
document.getElementById('findFirst').innerHTML =
'First number over 18 is ' + firstFind;
First number over 18 is 25