JavaScript gives us several tools for iterating over the items in an array. We could have used a for loop, and it's arguably much simpler. There are no complicated callback functions.
Taken as a whole, this family of array methods allows us to do all sorts of amazing things, like finding a particular item in the array, filtering a list, and much more.
All of the methods in this family follow the same basic structure. For example, they all support the optional index parameter to obtain the index of the current element of the array.
This repository contains exercises and docs for using javascript array methods.
- some
- every
- map
- filter
- reduce
- forEach
- sort
- includes
- find
- findIndex
- indexOf
- concat
- slice
- splice
- push
- pop
- shift
- unshift
- reverse
- keys
- fill
The some()
method tests whether at least one element in the array passes the test implemented by the provided callback function. It returns true
if, in the array, it finds an element for which the provided function returns true; otherwise, it returns false
.
const numbers = [1, 2, 3, 4, 5];
// Checks whether a number is even
console.log(
numbers.some((number) => {
number % 2 === 0;
})
);
// Expected output: true
console.log([1, 13, 3, 7, 5].some((number) => number % 2 === 0));
// Expected output: false
The every()
method tests whether all elements in the array pass the test implemented by the provided callback function. It returns false
if, in the array, it finds an element for which the provided function returns false; otherwise, it returns true
.
const numbers = [1, 30, 39, 29];
// Checks whether all numbers are below a threshold
console.log(numbers.every((number) => number < 40));
// Expected output: true
console.log([1, 100, 39, 29].every((number) => number < 40));
// Expected output: false
The map()
creates a new array populated with the results of calling a provided function on every element in the calling array.
const people = [
{ name: 'Aisha', grade: 89 },
{ name: 'Bruno', grade: 55 },
{ name: 'Carlos', grade: 68 },
{ name: 'Dacian', grade: 71 },
{ name: 'Esther', grade: 40 },
];
// Pass a callback function to map
const resultArray = array1.map((number) => number * 2);
const screamedNames = people.map((person) => {
return person.name.toUpperCase();
});
console.log(screamedNames); // Expected output: Array ['AISHA', 'BRUNO','CARLOS', 'DACIAN', 'ESTHER']
The filter()
creates a referenced copy of a given array, removing the elements that do not pass the test implemented on the provided callback function. That callback function will be called once per item in the array and should return true
or false
. Based on that result, the element will be or not in the new array.
const words = [
'spray',
'limit',
'elite',
'exuberant',
'destruction',
'present',
];
const result = words.filter((word) => word.length > 6);
console.log(result); // Expected output: Array ["exuberant", "destruction", "present"]
The reduce()
method executes a user-supplied callback function on each element of the array passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0)
const numbers = [15.5, 2.3, 1.1, 4.7];
const initialValue = 0
const sum = numbers.reduce((total, num) {
return total + Math.round(num);
}, initialValue)
console.log(sum); // Expected output: 24
The forEach()
method executes a provided function (callback) once for each array element. In many ways, is quite a lot like map()
, the difference is that map()
produces a new array with the transformed values and forEach()
not (always returns undefined).
const items = ['item1', 'item2', 'item3'];
const itemsCopy = [];
items.forEach((item) => {
copyItems.push(item);
});
The sort()
method sorts the elements of an array and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
const numbers = [1, 30, 4, 21, 100000];
numbers.sort();
console.log(numbers);
// Expected output: Array [1, 100000, 21, 30, 4]
The includes()
method determines whether an array includes a certain value among its entries, returning true
or false
as appropriate.
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat')); // Expected output: true
console.log(pets.includes('at')); // Expected output: false
The find()
returns the first element in the provided array that satisfies the provided testing function.If no values satisfy the testing function, undefined is returned.
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find((element) => element > 10);
console.log(found); // Expected output: 12
The findIndex()
returns the index of the first element in an array that satisfies the provided testing function.If no elements satisfy the testing function, -1 is returned.
const numbers = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(numbers.findIndex(isLargeNumber)); // Expected output: 3
The indexOf()
returns the first index at which a given element can be found in the array or -1 if it is not present. You can also define a starting index.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison')); // Expected output: 1
const fromIndex = 2;
console.log(beasts.indexOf('bison', fromIndex)); // Expected output: 4
console.log(beasts.indexOf('giraffe')); // Expected output: -1
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
const firstArray = ['a', 'b', 'c'];
const secondArray = ['d', 'e', 'f'];
const thirdArray = firstArray.concat(secondArray);
console.log(thirdArray);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
The splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements.
const months = ['Jan', 'March', 'April', 'June'];
// Inserts at index 1
months.splice(1, 0, 'Feb');
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
// Replaces 1 element at index 4
months.splice(4, 1, 'May');
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]
The push()
method adds the specified element/s to the end of an array and returns the new length of the array
const animals = ['pigs', 'goats', 'sheep'];
let length = animals.push('cows');
console.log(length); // Expected output: 4
console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows"]
length = animals.push('chickens', 'cats', 'dogs');
console.log(length); // Expected output: 7
console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
The pop()
method removes the last element from an array and returns that element. This method changes the length of the array.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop()); // Expected output: "tomato"
console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage"]
The shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.
const numbers = [1, 2, 3];
const firstElement = numbers.shift();
console.log(numbers);
// Expected output: Array [2, 3]
console.log(firstElement);
// Expected output: 1
The unshift()
method adds the specified elements to the beginning of an array and returns the new length of the array.
const numbers = [1, 2, 3];
console.log(numbers.unshift(4, 5)); // Expected output: 5
console.log(numbers);
// Expected output: Array [4, 5, 1, 2, 3]
The reverse()
method reverses an array in place and returns the original array modified (a reference to it). The first array element now becomes the last, and the last array element becomes the first.
To reverse the elements in an array without mutating the original array, use toReversed()
const array> = ['one', 'two', 'three'];
console.log('array:', array); // Expected output: "array:" Array ["one", "two", "three"]
const reversed = array.reverse();
console.log('reversed:', reversed); // Expected output: "reversed:" Array ["three", "two", "one"]
// Careful: array.reverse() is destructive -- it changes the original array.
console.log('array:', array); // Expected output: "array:" Array ["three", "two", "one"]
The keys()
method returns a new array iterator object that contains the keys for each index in the array.
const numbers = ['a', 'b', 'c'];
const iterator = numbers.keys();
for (const key of iterator) {
console.log(key);
}
// Expected output: 0
// Expected output: 1
// Expected output: 2
The fill()
method changes all elements within a range of indices in an array to a static value. It returns the modified array. If you call the method without specifying start & end index, it will fill the entire array with the specified value.
const numbers = [1, 2, 3, 4];
// Fill with 0 from position 2 until position 4
console.log(numbers.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]
// Fill with 5 from position 1
console.log(numbers.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]
// Replace all the elements of the array
console.log(numbers.fill(6));
// Expected output: Array [6, 6, 6, 6]