Array Methods
Array Methods
ARعربي
ENEnglish
ESEspañol
FAفارسی
FRFrançais
IDIndonesia
ITItaliano
JA日本語
KO한국어
RUРусский
TRTürkçe
UKУкраїнська
UZOʻzbek
ZH简体中文
We want to make this open-source project available for people all around the world.
BuyEPUB/PDF
Search on [Link]
Search
Search in the tutorial Search
Tutorial map
Light themeDark theme
Share
English
1. Tutorial
2. The JavaScript language
3. Data types
Array methods
Arrays provide a lot of methods. To make things easier, in this chapter, they are split into groups.
Add/remove items
We already know methods that add and remove items from the beginning or the end:
splice
The element was removed, but the array still has 3 elements, we can see that [Link] == 3.
That’s natural, because delete [Link] removes a value by the key. It’s all it does. Fine for objects. But for arrays we usually want the rest of the elements to shift and occupy the freed place. We expect to have a shorter array now.
The [Link] method is a Swiss army knife for arrays. It can do everything: insert, remove and replace elements.
It modifies arr starting from the index start: removes deleteCount elements and then inserts elem1, ..., elemN at their place. Returns the array of removed elements.
In the next example, we remove 3 elements and replace them with the other two:
Here we can see that splice returns the array of removed elements:
let arr = ["I", "study", "JavaScript", "right", "now"];
The splice method is also able to insert the elements without any removals. For that, we need to set deleteCount to 0:
let arr = ["I", "study", "JavaScript"];
// from index 2
// delete 0
// then insert "complex" and "language"
[Link](2, 0, "complex", "language");
Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here:
slice
[Link]([start], [end])
It returns a new array copying to it all items from index start to end (not including end). Both start and end can be negative, in that case position from array end is assumed.
It’s similar to a string method [Link], but instead of substrings, it makes subarrays.
For instance:
let arr = ["t", "e", "s", "t"];
We can also call it without arguments: [Link]() creates a copy of arr. That’s often used to obtain a copy for further transformations that should not affect the original array.
concat
The method [Link] creates a new array that includes values from other arrays and additional items.
[Link](arg1, arg2...)
The result is a new array containing items from arr, then arg1, arg2 etc.
If an argument argN is an array, then all its elements are copied. Otherwise, the argument itself is copied.
For instance:
let arr = [1, 2];
// create an array from: arr and [3,4], then add values 5 and 6
alert( [Link]([3, 4], 5, 6) ); // 1,2,3,4,5,6
Normally, it only copies elements from arrays. Other objects, even if they look like arrays, are added as a whole:
let arrayLike = {
0: "something",
length: 1
};
…But if an array-like object has a special [Link] property, then it’s treated as an array by concat: its elements are added instead:
let arrayLike = {
0: "something",
1: "else",
[[Link]]: true,
length: 2
};
Iterate: forEach
The [Link] method allows to run a function for every element of the array.
The syntax:
[Link](function(item, index, array) {
// ... do something with an item
});
And this code is more elaborate about their positions in the target array:
The result of the function (if it returns any) is thrown away and ignored.
Searching in array
Now let’s cover methods that search in an array.
The methods [Link] and [Link] have the similar syntax and do essentially the same as their string counterparts, but operate on items instead of characters:
[Link](item, from) – looks for item starting from index from, and returns the index where it was found, otherwise -1.
[Link](item, from) – looks for item starting from index from, returns true if found.
Usually, these methods are used with only one argument: the item to search. By default, the search is from the beginning.
For instance:
let arr = [1, 0, false];
alert( [Link](0) ); // 1
alert( [Link](false) ); // 2
alert( [Link](null) ); // -1
Please note that indexOf uses the strict equality === for comparison. So, if we look for false, it finds exactly false and not the zero.
If we want to check if item exists in the array and don’t need the index, then [Link] is preferred.
The method [Link] is the same as indexOf, but looks for from right to left.
A minor, but noteworthy feature of includes is that it correctly handles NaN, unlike indexOf:
That’s because includes was added to JavaScript much later and uses the more up-to-date comparison algorithm internally.
Imagine we have an array of objects. How do we find an object with a specific condition?
The function is called for elements of the array, one after another:
If it returns true, the search is stopped, the item is returned. If nothing is found, undefined is returned.
For example, we have an array of users, each with the fields id and name. Let’s find the one with id == 1:
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
alert([Link]); // John
In real life, arrays of objects are a common thing, so the find method is very useful.
Note that in the example we provide to find the function item => [Link] == 1 with one argument. That’s typical, other arguments of this function are rarely used.
The [Link] method has the same syntax but returns the index where the element was found instead of the element itself. The value of -1 is returned if nothing is found.
The [Link] method is like findIndex, but searches from right to left, similar to lastIndexOf.
Here’s an example:
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"},
{id: 4, name: "John"}
];
filter
The find method looks for a single (first) element that makes the function return true.
The syntax is similar to find, but filter returns an array of all matching elements:
let results = [Link](function(item, index, array) {
// if true item is pushed to results and the iteration continues
// returns empty array if nothing found
});
For instance:
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
alert([Link]); // 2
Transform an array
Let’s move on to methods that transform and reorder an array.
map
The [Link] method is one of the most useful and often used.
It calls the function for each element of the array and returns the array of results.
sort(fn)
The call to [Link]() sorts the array in place, changing its element order.
It also returns the sorted array, but the returned value is usually ignored, as arr itself is modified.
For instance:
let arr = [ 1, 2, 15 ];
Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed "2" > "15".
To use our own sorting order, we need to supply a function as the argument of [Link]().
let arr = [ 1, 2, 15 ];
[Link](compareNumeric);
alert(arr); // 1, 2, 15
Let’s step aside and think about what’s happening. The arr can be an array of anything, right? It may contain numbers or strings or objects or whatever. We have a set of some items. To sort it, we need an ordering function that knows how to compare its elements. The default is a string order.
The [Link](fn) method implements a generic sorting algorithm. We don’t need to care how it internally works (an optimized quicksort or Timsort most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the fn which
does the comparison.
By the way, if we ever want to know which elements are compared – nothing prevents us from alerting them:
The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible.
Actually, a comparison function is only required to return a positive number to say “greater” and a negative number to say “less”.
alert(arr); // 1, 2, 15
Remember arrow functions? We can use them here for neater sorting:
[Link]( (a, b) => a - b );
For many alphabets, it’s better to use [Link] method to correctly sort letters, such as Ö.
alert( [Link]( (a, b) => a > b ? 1 : -1) ); // Andorra, Vietnam, Österreich (wrong)
reverse
For instance:
Here’s the situation from real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: John, Pete, Mary. But for us an array of names would be much more comfortable than a single string. How to get it?
The [Link](delim) method does exactly that. It splits the string into an array by the given delimiter delim.
The split method has an optional second numeric argument – a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though:
let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2);
The call to split(s) with an empty s would split the string into an array of letters:
let str = "test";
The call [Link](glue) does the reverse to split. It creates a string of arr items joined by glue between them.
For instance:
let arr = ['Bilbo', 'Gandalf', 'Nazgul'];
reduce/reduceRight
When we need to iterate over an array – we can use forEach, for or for..of.
When we need to iterate and return the data for each element – we can use map.
The methods [Link] and [Link] also belong to that breed, but are a little bit more intricate. They are used to calculate a single value based on the array.
The function is applied to all array elements one after another and “carries on” its result to the next call.
Arguments:
accumulator – is the result of the previous function call, equals initial the first time (if initial is provided).
item – is the current array item.
index – is its position.
array – is the array.
As the function is applied, the result of the previous function call is passed to the next one as the first argument.
So, the first argument is essentially the accumulator that stores the combined result of all previous executions. And at the end, it becomes the result of reduce.
Sounds complicated?
alert(result); // 15
The function passed to reduce uses only 2 arguments, that’s typically enough.
1. On the first run, sum is the initial value (the last argument of reduce), equals 0, and current is the first array element, equals 1. So the function result is 1.
2. On the second run, sum = 1, we add the second array element (2) to it and return.
3. On the 3rd run, sum = 3 and we add one more element to it, and so on…
Or in the form of a table, where each row represents a function call on the next array element:
Here we can clearly see how the result of the previous call becomes the first argument of the next one.
alert( result ); // 15
The result is the same. That’s because if there’s no initial, then reduce takes the first element of the array as the initial value and starts the iteration from the 2nd element.
The calculation table is the same as above, minus the first row.
But such use requires an extreme care. If the array is empty, then reduce call without initial value gives an error.
Here’s an example:
let arr = [];
The method [Link] does the same but goes from right to left.
[Link]
Arrays do not form a separate language type. They are based on objects.
…But arrays are used so often that there’s a special method for that: [Link](value). It returns true if the value is an array, and false otherwise.
alert([Link]({})); // false
alert([Link]([])); // true
That parameter is not explained in the sections above, because it’s rarely used. But for completeness, we have to cover it.
For example, here we use a method of army object as a filter, and thisArg passes the context:
let army = {
minAge: 18,
maxAge: 27,
canJoin(user) {
return [Link] >= [Link] && [Link] < [Link];
}
};
let users = [
{age: 16},
{age: 20},
{age: 23},
{age: 30}
];
alert([Link]); // 2
alert(soldiers[0].age); // 20
alert(soldiers[1].age); // 23
If in the example above we used [Link]([Link]), then [Link] would be called as a standalone function, with this=undefined, thus leading to an instant error.
A call to [Link]([Link], army) can be replaced with [Link](user => [Link](user)), that does the same. The latter is used more often, as it’s a bit easier to understand for most people.
Summary
A cheat sheet of array methods:
To add/remove elements:
indexOf/lastIndexOf(item, pos) – look for item starting from position pos, and return the index or -1 if not found.
includes(value) – returns true if the array has value, otherwise false.
find/filter(func) – filter elements through the function, return first/all values that make it return true.
findIndex is like find, but returns the index instead of a value.
forEach(func) – calls func for every element, does not return anything.
map(func) – creates a new array from results of calling func for every element.
sort(func) – sorts the array in-place, then returns it.
reverse() – reverses the array in-place, then returns it.
split/join – convert a string to array and back.
reduce/reduceRight(func, initial) – calculate a single value over the array by calling func for each element and passing an intermediate result between the calls.
Additionally:
[Link](value) checks value for being an array, if so returns true, otherwise false.
Please note that methods sort, reverse and splice modify the array itself.
These methods are the most used ones, they cover 99% of use cases. But there are few others:
The function fn is called on each element of the array similar to map. If any/all results are true, returns true, otherwise false.
These methods behave sort of like || and && operators: if fn returns a truthy value, [Link]() immediately returns true and stops iterating over the rest of items; if fn returns a falsy value, [Link]() immediately returns false and stops iterating over the rest of items as well.
[Link](value, start, end) – fills the array with repeating value from index start to end.
[Link](target, start, end) – copies its elements from position start till position end into itself, at position target (overwrites existing).
At first sight, it may seem that there are so many methods, quite difficult to remember. But actually, that’s much easier.
Look through the cheat sheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods.
Afterwards whenever you need to do something with an array, and you don’t know how – come here, look at the cheat sheet and find the right method. Examples will help you to write it correctly. Soon you’ll automatically remember the methods, without specific efforts from your side.
Tasks
Translate border-left-width to borderLeftWidth
importance: 5
Write the function camelize(str) that changes dash-separated words like “my-short-string” into camel-cased “myShortString”.
That is: removes all dashes, each word after dash becomes uppercased.
Examples:
camelize("background-color") == 'backgroundColor';
camelize("list-style-image") == 'listStyleImage';
camelize("-webkit-transition") == 'WebkitTransition';
P.S. Hint: use split to split the string into an array, transform it and join back.
solution
function camelize(str) {
return str
.split('-') // splits 'my-long-word' into array ['my', 'long', 'word']
.map(
// capitalizes first letters of all array items except the first one
// converts ['my', 'long', 'word'] into ['my', 'Long', 'Word']
(word, index) => index == 0 ? word : word[0].toUpperCase() + [Link](1)
)
.join(''); // joins ['my', 'Long', 'Word'] into 'myLongWord'
}
Filter range
importance: 4
Write a function filterRange(arr, a, b) that gets an array arr, looks for elements with values higher or equal to a and lower or equal to b and return a result as an array.
The function should not modify the array. It should return the new array.
For instance:
let arr = [5, 3, 8, 1];
solution
function filterRange(arr, a, b) {
// added brackets around the expression for better readability
return [Link](item => (a <= item && item <= b));
}
importance: 4
Write a function filterRangeInPlace(arr, a, b) that gets an array arr and removes from it all values except those that are between a and b. The test is: a ≤ arr[i] ≤ b.
The function should only modify the array. It should not return anything.
For instance:
let arr = [5, 3, 8, 1];
solution
function filterRangeInPlace(arr, a, b) {
solution
alert( arr );
importance: 5
We have an array of strings arr. We’d like to have a sorted copy of it, but keep arr unmodified.
solution
We can use slice() to make a copy and run the sort on it:
function copySorted(arr) {
return [Link]().sort();
}
alert( sorted );
alert( arr );
importance: 5
1. First, implement the method calculate(str) that takes a string like "1 + 2" in the format “NUMBER operator NUMBER” (space-delimited) and returns the result. Should understand plus + and minus -.
Usage example:
let calc = new Calculator;
2. Then add the method addMethod(name, func) that teaches the calculator a new operation. It takes the operator name and the two-argument function func(a,b) that implements it.
For instance, let’s add the multiplication *, division / and power **:
let powerCalc = new Calculator;
[Link]("*", (a, b) => a * b);
[Link]("/", (a, b) => a / b);
[Link]("**", (a, b) => a ** b);
solution
Please note how methods are stored. They are simply added to [Link] property.
All tests and numeric conversions are done in the calculate method. In future it may be extended to support more complex expressions.
function Calculator() {
[Link] = {
"-": (a, b) => a - b,
"+": (a, b) => a + b
};
[Link] = function(str) {
Map to names
importance: 5
You have an array of user objects, each one has [Link]. Write the code that converts it into an array of names.
For instance:
solution
Map to objects
importance: 5
You have an array of user objects, each one has name, surname and id.
Write the code to create another array from it, of objects with id and fullName, where fullName is generated from name and surname.
For instance:
/*
usersMapped = [
{ fullName: "John Smith", id: 1 },
{ fullName: "Pete Hunt", id: 2 },
{ fullName: "Mary Key", id: 3 }
]
*/
alert( usersMapped[0].id ) // 1
alert( usersMapped[0].fullName ) // John Smith
So, actually you need to map one array of objects to another. Try using => here. There’s a small catch.
solution
/*
usersMapped = [
{ fullName: "John Smith", id: 1 },
{ fullName: "Pete Hunt", id: 2 },
{ fullName: "Mary Key", id: 3 }
]
*/
alert( usersMapped[0].id ); // 1
alert( usersMapped[0].fullName ); // John Smith
Please note that in the arrow functions we need to use additional brackets.
As we remember, there are two arrow functions: without body value => expr and with body value => {...}.
Here JavaScript would treat { as the start of function body, not the start of the object. The workaround is to wrap them in the “normal” brackets:
let usersMapped = [Link](user => ({
fullName: `${[Link]} ${[Link]}`,
id: [Link]
}));
Now fine.
Write the function sortByAge(users) that gets an array of objects with the age property and sorts them by age.
For instance:
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 28 };
sortByAge(arr);
solution
function sortByAge(arr) {
[Link]((a, b) => [Link] - [Link]);
}
sortByAge(arr);
Shuffle an array
importance: 3
Write the function shuffle(array) that shuffles (randomly reorders) elements of the array.
Multiple runs of shuffle may lead to different orders of elements. For instance:
let arr = [1, 2, 3];
shuffle(arr);
// arr = [3, 2, 1]
shuffle(arr);
// arr = [2, 1, 3]
shuffle(arr);
// arr = [3, 1, 2]
// ...
All element orders should have an equal probability. For instance, [1,2,3] can be reordered as [1,2,3] or [1,3,2] or [3,1,2] etc, with equal probability of each case.
solution
That somewhat works, because [Link]() - 0.5 is a random number that may be positive or negative, so the sorting function reorders elements randomly.
But because the sorting function is not meant to be used this way, not all permutations have the same probability.
For instance, consider the code below. It runs shuffle 1000000 times and counts appearances of all possible results:
function shuffle(array) {
[Link](() => [Link]() - 0.5);
}
123: 250706
132: 124425
213: 249618
231: 124880
312: 125148
321: 125223
We can see the bias clearly: 123 and 213 appear much more often than others.
The result of the code may vary between JavaScript engines, but we can already see that the approach is unreliable.
Why it doesn’t work? Generally speaking, sort is a “black box”: we throw an array and a comparison function into it and expect the array to be sorted. But due to the utter randomness of the comparison the black box goes mad, and how exactly it goes mad depends on the concrete
implementation that differs between engines.
There are other good ways to do the task. For instance, there’s a great algorithm called Fisher-Yates shuffle. The idea is to walk the array in the reverse order and swap each element with a random one before it:
function shuffle(array) {
for (let i = [Link] - 1; i > 0; i--) {
let j = [Link]([Link]() * (i + 1)); // random index from 0 to i
Looks good now: all permutations appear with the same probability.
Also, performance-wise the Fisher-Yates algorithm is much better, there’s no “sorting” overhead.
Write the function getAverageAge(users) that gets an array of objects with property age and returns the average age.
For instance:
let john = { name: "John", age: 25 };
let pete = { name: "Pete", age: 30 };
let mary = { name: "Mary", age: 29 };
solution
function getAverageAge(users) {
return [Link]((prev, user) => prev + [Link], 0) / [Link];
}
alert( getAverageAge(arr) ); // 28
importance: 4
Create a function unique(arr) that should return an array with unique items of arr.
For instance:
function unique(arr) {
/* your code */
}
solution
For each item we’ll check if the resulting array already has that item.
If it is so, then ignore, otherwise add to results.
function unique(arr) {
let result = [];
return result;
}
The method [Link](str) internally walks the array result and compares each element against str to find the match.
So if there are 100 elements in result and no one matches str, then it will walk the whole result and do exactly 100 comparisons. And if result is large, like 10000, then there would be 10000 comparisons.
That’s not a problem by itself, because JavaScript engines are very fast, so walk 10000 array is a matter of microseconds.
But we do such test for each element of arr, in the for loop.
So if [Link] is 10000 we’ll have something like 10000*10000 = 100 millions of comparisons. That’s a lot.
Further in the chapter Map and Set we’ll see how to optimize it.
importance: 4
Let’s say we received an array of users in the form {id:..., name:..., age:... }.
Create a function groupById(arr) that creates an object from it, with id as the key, and array items as values.
For example:
let users = [
{id: 'john', name: "John Smith", age: 20},
{id: 'ann', name: "Ann Smith", age: 24},
{id: 'pete', name: "Pete Peterson", age: 31},
];
/*
// after the call we should have:
usersById = {
john: {id: 'john', name: "John Smith", age: 20},
ann: {id: 'ann', name: "Ann Smith", age: 24},
pete: {id: 'pete', name: "Pete Peterson", age: 31},
}
*/
In this task we assume that id is unique. There may be no two array items with the same id.
solution
function groupById(array) {
return [Link]((obj, value) => {
obj[[Link]] = value;
return obj;
}, {})
}
Comments
read this before commenting…
If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
If you can't understand something in the article – please elaborate.
To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)
POWERED BY
Chapter
Data types
Lesson navigation
Add/remove items
Iterate: forEach
Searching in array
Transform an array
[Link]
Most methods support “thisArg”
Summary
Tasks (13)
Comments
Share
Edit on GitHub