The matrices can be manipulated thanks to different methods that today I am going to explain some of them, since this topic is very easy. Let's get started!
Add / remove items
We already know methods that add and remove elements from the beginning or the end:
- arr.push (… items) - add elements to the end,
- arr.pop () - Extract an article from the end,
- arr.shift () - Extract an article from the beginning,
- arr.unshift (… items) - Add elements at the beginning.
However, here are a few others.
Splice
How to remove an element from the array?
Arrays are objects, so we can try to use delete:
let arr = ["I want", "eat", "now"]; delete arr [2]; // remove "now" alert (arr [2]); // undefined // now arr = ["I want", "eat",]; alert (arr.length); // 3
The element was removed, but the array still has 3 elements, we can see that arr.length == 3.
That is natural, because delete obj.key remove a value for the key. It's all it does. Good for objects. But for the arrangements we generally want the rest of the elements to move and occupy the freed place. We hope to have a shorter matrix now.
Therefore, special methods must be used.
The method arr.splice (str) It is like a Swiss Army Knife for arrangements. You can do everything: add, remove, and insert items.
The syntax is:
arr.splice (index [, deleteCount, elem1, ..., elemN])
Comienza desde la posición index: deleteCount elementos y luego los inserta elem1, …, elemN en su lugar. Devuelve la matriz de elementos eliminados.
This method is easy to understand using examples.
Let's start with the removal:
let arr = ["I", "study", "JavaScript"]; arr.splice (1, 1); // from index 1 remove 1 element alert (arr); // ["I", "JavaScript"]
Easy right? Starting at index 1, element 1 was eliminated.
In the following example, we remove 3 items and replace them with the other two:
let arr = ["I", "study", "JavaScript", "now", "same"]; // remove the first 3 elements and replace them with another arr.splice (0, 3, "We", "we danced"); alert (arr) // now ["We", "we dance", "now", "same"]
Here we can see that splice returns the array of removed items:
let arr = ["I", "study", "JavaScript", "now", "same"]; // remove the first two elements let removed = arr.splice (0, 2); alert (removed); // "YoI", "study" <- set of elements removed
The method splice It is also capable of inserting the elements without any deletion. For that we have to configure deleteCount to 0:
let arr = ["I", "study", "JavaScript"]; // from index 2 // delete 0 // then insert "complex" and "language". //arr.splice(2, 0, "complex", "language"); alert (arr); // "I", "study", "language", "complex", "JavaScript"
Negative indices are allowed
Here and in other array methods, negative indices are allowed. They specify the position from the end of the array, like here:
let arr = [1, 2, 5]; // from index -1 (one step from the end) // delete 0 elements, // then add points 3 and 4 splice.array (-1, 0, 3, 4); alert (arr); // 1,2,3,4,5
Slice
The method arr.slice it is much simpler than the similar arr.splice.
The syntax is:
arr.slice (beginning, end);
Returns a new array where it copies all elements beginning index "beginning" to "end" (not including "end"). Both beginning and end can be negative, in that case the position from the end of the array is assumed.
For example:
let str = "test"; let arr = ["t", "e", "s", "t"]; alert (str.slice (1, 3)); // is alert (arr.slice (1, 3)); // e, s alert (str.slice (-2)); // st alert (arr.slice (-2)); // s, t concat
The method arr.concat unites the matrix with other matrices and / or elements.
The syntax is:
arr.concat (arg1, arg2 ...)
Acepta cualquier número de argumentos, ya be matrices o valores.
The result is a new array containing elements from arr, so arg1, arg2etc.
If an argument is an array or has a Symbol.isConcatSpreadable property, then all of its elements are copied. Otherwise, the argument itself is copied.
For example:
let arr = [1, 2]; // merge arr with [3,4] alert (arr.concat ([3, 4])); // 1,2,3,4 // merge arr with [3,4] and [5,6] alert (arr.concat ([3, 4], [5, 6])); // 1,2,3,4,5,6 // merge arr with [3,4], then add the values 5 and 6 alert (arr.concat ([3, 4], 5, 6)); // 1,2,3,4,5,6
Normally, it just copies the elements of the arrays ("extends" them). Other objects, even if they look like arrays, added as a whole:
let arr = [1, 2]; let arrayHello = {0: "some", length: 1}; alert (arr.concat (arrayHello)); // 1,2, [object Object] // [1, 2, arrayLike]
But if an array-like object has Symbol.is, Concat, Spreadable properties, then its elements are added instead:
let arr = [1, 2]; let arrayHello = {0: "some", 1: "flaso", [Symbol.isConcatSpreadable]: true, length: 2}; alert (arr.concat (arrayHello)); // 1,2, some, false
Searching the matrix
These are methods of searching for something in an array.
indexOf / lastIndexOf and Includes
Methods arr.indexOf , arr.lastIndexOf and arr.includes They have the same syntax and do essentially the same thing as their string counterparts, but they operate on elements rather than characters:
- arr.indexOf (item, from) look for a item from index since, and returns the index where it was found, otherwise -1.
- arr.lastIndexOf (item, from) - Same, but look from right to left.
- arr.includes (item, from)- Look for item from index desde, and returns true if found.
For example:
let arr = [1, 0, false]; alert (arr.indexOf (0)); // 1 alert (arr.indexOf (false)); // 2 alert (arr.indexOf (null)); // -1 alert (arr.includes (1)); // true
Note that the methods use comparison ===. So if we search for false, it finds exactly false and not zero.
If we want to check for inclusion and we don't want to know the exact index, then arr.includes It is preferable.
Also, a very small difference from includes is that it handles correctly NaN, Unlike indexOf / lastIndexOf:
const arr = [NaN]; alert (arr.indexOf (NaN)); // -1 (should be 0, but ==== equality doesn't work for NaN) alert (arr.includes (NaN)); // true (correct)
find and findIndex
Imagine that we have a variety of objects. How do we find an object with the specific condition?
Here the method arr.find It is useful.
The syntax is:
let result = arr.find (function (item, index, array) {// should return true if the item is what we are looking for});
The function is called repetitively for each element of the array:
- item is the element
- index is your index.
- array it is the womb itself.
If he comes back true, the search stops, item It is returned. If nothing is found, undefined It is returned.
For example, we have an array of users, each with the id and name fields. Let's find the one with id == 1:
let users = [{id: 1, name: "Juan"}, {id: 2, name: "Pedro"}, {id: 3, name: "Maria"}]; let users = users.find (item => item.id == 1); alert (users.name); // John
In real life, object arrangements are a common thing, so the find method it is very useful.
Note that in the example we provided of a function find single argument item => item.id == 1. Other parameters of find they are rarely used.
The arr.findIndex method is essentially the same, but it returns the index where the item was found rather than the item itself.
Filter
The find method searches for a single (first) element that makes the function return true.
If there can be many, we can use arr.filter (fn).
The syntax is roughly the same as find, but it returns an array of matching elements:
let result = arr.filter (function (item, index, array) {// should return true if the item passes the filter});
For example:
let users = [{id: 1, name: "Juan"}, {id: 2, name: "Pedro"}, {id: 3, name: "Maria"}]; // return the array of the first users let someUsers = users.filter (item => item.id <3); alert (someUsers.length); // two