Access and change elements of one Array
let array =["a", "b", "c"];
console.log(array[1])// "b";
array[2]="d";
console.log(array);// ["a", "b", "d"]
Important Array Methods
forEach
The array method forEach executes some logic for each element within an array.
const pets = ["bird", "cat", "dog", "fish"];
pets.forEach((pet) => {
const petElement = document.createElement("p");
petElement.textContent = pet;
document.body.append(petElement);
});
map
The array method map is used to apply a transformation to each element of an array.
The transformed elements are stored in the newly created array returned by map. The elements in the original array are not being altered.The created and the original array have the same length.
const pets = ["bird", "cat", "dog", "fish"];
const uppercasePets = pets.map((pet) => {
return pet.toUpperCase();
});
console.log(uppercasePets);
// ['BIRD', 'CAT', 'DOG', 'FISH']
The callback function provided to map must use a return statement to return a transformed element. map returns a new array.
You should not use map to trigger a side-effect, like document.createElement
filter
The array method filter is used to create a new array with a subset of the elements of the original array. The callback function returns a boolean value to define, if an element is being included in the resulting array or not. The original array is not being altered
const pets = ["bird", "cat", "dog", "ferret", "fish"];
const petsWithF = pets.filter((pet) => {
return pet.startsWith("f");
});
console.log(petsWithF);
// ['fish']
The callback function provided to filter must use a return statement to return a boolean value.
Chaining array methods
Often times you need to combine multiple array methods to achieve a desired result. Array methods like map and filter, that return a new array, can be chained.
Instead of storing each array in a separated variable, the methods can be called directly after another. This reduces the amount of code and improves readable.
const pets = ["bird", "cat", "dog", "ferret", "fish"];
const uppercasePetsWithF = pets
.filter((pet) => {
return pet.startsWith("f");
})
.map((pet) => {
return pet.toUpperCase();
});
console.log(uppercasePetsWithF);
// ['FERRET', 'FISH']
document.querySelectorAll
The NodeList returned by document.querySelectorAll is an array-like object. You can use the forEach method to iterate over the DOM elements.
const pets = document.querySelectorAll('[data-js="pet"]');
pets.forEach((pet) => {
pet.addEventListener("click", () => {
// [...]
});
});
A NodeList is not an array! Other array methods like map
or filter
can't be used. If you need to use array methods, you can convert the NodeList to an array using Array.from()
includes
Use array.includes() to check whether the array contains the specified value. If it does, true is returned, otherwise false.
const colors = ["red", "yellow", "green"];
colors.includes("yellow"); // true
colors.includes("blue"); // false
find
and findIndex
Use find() to receive the first element of the array that satisfies the provided testing function. Otherwise, it returns undefined.
const colors = ["red", "yellow", "green"];
colors.find((color) => color.startsWith("g")); // 'green'
colors.find((color) => color.startsWith("b")); // undefined
Use findIndex() to receive the index of the first element of the array that satisfies the provided testing function. If there is no such element, -1 is returned.
const colors = ["red", "yellow", "green"];
colors.findIndex((color) => color.startsWith("y")); // 1
colors.findIndex((color) => color.startsWith("b")); // -1
sort
and reverse
Use sort()
to sort the elements of an array. You need to provide a callback function in order to tell how the array is sorted.
sort() converts the elements into strings, then compares their sequences of UTF-16 Code units values. This is why array.sort() without a callback is mostly useless.
const numbers = [4, 42, 23, 1];
numbers.sort((a, b) => a - b);
// [1, 4, 23, 42]
numbers.sort((a, b) => b - a);
// [42, 23, 4, 1]
sort() two things inside of the callback function with strings:
1.- lowercase both strings before comparing them (uppercase works as well)
2.- using if-statements, be explicit about the return values dependent on the result of the comparison (nameA < nameB and nameA > nameB)
(In UTF-16, the upper- and lowercase version of the same letter do not have the same value)
const strings = ["Ana", "Peter", "Gaia"];
strings.sort((a, b) => {
const nameA = a.toLowerCase();
const nameB = b.toLowerCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
console.log(strings);
// ['Ana', 'Gaia', 'Peter']
use reverse
to reverse an array, simply use array.reverse(). This can be combined with sort() as well:
const numbers = [4, 42, 23, 1];
const reversedNumbers = numbers.reverse();
// [1, 23, 42, 4]
slice
It's important to note that some array methods, as sort(), do not create a new array, but mutate the original one.
This behaviour will often cause errors. To prevent it, just make a copy of the original array using slice().
const numbers = [4, 42, 23, 1];
console.log(numbers); // [4, 42, 23, 1]
const sortedNumbers = numbers.slice().sort((a, b) => a - b);
console.log(sortedNumbers); // [1, 4, 23, 42]
console.log(numbers); // [4, 42, 23,
some
and every
Use some() to test whether at least one element in the array passes the provided test.
const colors = ["red", "yellow", "green"];
colors.some((color) => color.startsWith("g")); // true
colors.some((color) => color.startsWith("i")); // false
In order to check if all elements pass the test, use every().
const colors = ["red", "yellow", "green"];
colors.every((color) => color.length > 2); // true
colors.every((color) => color.length < 1); // false
reduce
is an array method to reduce a list of values into a single value.
It's main use case is to calculate the sum of an array of numbers.
starting from the beginning, it executes the callback function on each element of the array, the return value of each calculation is passed to the next calculation (i.e. it becomes the new starting value for the next iteration through the array)the final result is a single value.
const numbers = [4, 42, 23, 1];
numbers.reduce((a, b) => a + b);
console.log(numbers); // 70
How to use the Methods and propierties
const array = ["a", "b", "c", "d"]
console.log(array.length);
// 4 //Output is a number. first element is 1 // length is a property
console.log(array.indexOf("d"));
// 3 //Output is a number. first Index is 0
console.log(array.push("e", "f"));
//["a", "b", "c", "d", "e", "f"]// add behind
console.log(array.pop())
//["a", "b", "c", "d", "e"]// Remove the last one and you can save it in one variable
console.log(array.shift())
//["b", "c", "d", "e"]// Remove before and you can save it in one variable
console.log(array.unshift("x", "y"))
//["x", "y", "b", "c", "d", "e"]// Add before
const text = "Hello JS friends"
console.log(text.split())
//["Hello JS friends"]//Convert to Array
console.log(text.split(""))
//['H', 'e', 'l', 'l', 'o', ' ', 'J', 'S', ' ', 'f', 'r', 'i', 'e', 'n', 'd', 's']//Every single element, space too
console.log(text.split(" "))
// ['Hello', 'JS', 'friends']//Separate where space are
console.log(text.split(" ").join(" "))
//"Hello JS friends"//Add the elements with (join) with one space (" ") between
console.log(text.split(" ")
const newArray = ["m", "n", "o", "p", "q"]
console.log(newArray.slice(1, 3))
//['n', 'o']//
first index is included, last one NO
const otherArray = ["i", "j", "k", "l"]
console.log(otherArray.splice(1, 2, "newItem"));
//['j', 'k'] // array.splice(startIndex, deleteCount(how many), item1, ...) we obtain the rest of the array. After that our Array is changed
console.log(otherArray)
//['i', 'newItem', 'l']
const numbersArray= [1, 5, 6, 3, 12]
console.log(numbersArray.reverse())
//[12, 3, 6, 5, 1]
console.log(numbersArray.sort())
//[1, 12, 3, 5, 6]//ASCII sort//Change original Array, recomended to use .slice() before .sort to do a copy
console.log(numbersArray.sort((a, b) => a - b))
// [1, 3, 5, 6, 12] //Change original Array, recomended to use .slice() before .sort to do a copy
Ascendet
console.log(numbersArray.sort((a, b) => b - a))
//[12, 6, 5, 3, 1] //Change original Array, recomended to use .slice() before .sort to do a copy
Descendent
const fruits = ["apple", "banana", "kiwi"];
fruits.forEach((fruit) => console.log(fruit))
//apple; banana; kiwi;// All items in new lines
const oddNumbers = [3, 5, 7]
let evenNumbers = oddNumbers.map((element)=> element+1); console.log(evenNumbers)
//[4, 6, 8]//
Return a Value and a new Array
Other Important: .include(); .filter(); .every(); .find(); .reduce();
3 ways to remove duplicates
const chars = ['A', 'B', 'A', 'C', 'B'];
Use Set
const uniqueChars = [...new Set(chars)];
console.log(uniqueChars);// Output: ['A', 'B', 'C']
Using the indexOf() and filter() methods
The indexOf() method returns the index of the first occurrence of the element in the array. The duplicate element is the element whose index is different from its indexOf() value. To eliminate duplicates, the filter() method is used to include only the elements whose indexes match their indexOf values, since we know that the filer method returns a new array based on the operations performed on it:
const uniqueChars = chars.filter((element, index) => {
return chars.indexOf(element) === index;
});
console.log(uniqueChars);//Output: ['A', 'B', 'C']
And if by chance we need the duplicates, we can modify our function a little, just by changing our rule:
const dupChars = chars.filter((element, index) => {
return chars.indexOf(element) !== index;
});
console.log(dupChars);//Output: ['A', 'B']
Using the includes() and forEach() methods
The include() function returns true if an element is in an array or false if it is not. The following example iterates over the elements of an array and adds to a new array only the elements that are not already there
const uniqueChars = [];
chars.forEach((element) => {
if (!uniqueChars.includes(element)) {
uniqueChars.push(element);
}
});
console.log(uniqueChars);//Output: ['A', 'B', 'C']