Array Methods
Array Methods
EN
December 6, 2022
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
1 let arr = ["I", "go", "home"];
2
3 delete arr[1]; // remove "go"
4
5 alert( arr[1] ); // undefined
6
7 // now arr = ["I", , "home"];
8 alert( arr.length ); // 3
The element was removed, but the array still has 3 elements, we can see that arr.length == 3 .
That’s natural, because delete obj.key removes a value by the key . It’s all it does. Fine for objects. But for arrays we
usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now.
The arr.splice method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements.
1 let arr = ["I", "study", "JavaScript"];
2
3 arr.splice(1, 1); // from index 1 remove 1 element
4
5 alert( arr ); // ["I", "JavaScript"]
In the next example we remove 3 elements and replace them with the other two:
1 let arr = ["I", "study", "JavaScript", "right", "now"];
2
3 // remove 3 first elements and replace them with another
4 arr.splice(0, 3, "Let's", "dance");
5
6 alert( arr ) // now ["Let's", "dance", "right", "now"]
Here we can see that splice returns the array of removed elements:
1 let arr = ["I", "study", "JavaScript", "right", "now"];
2
3 // remove 2 first elements
4 let removed = arr.splice(0, 2);
5
6 alert( removed ); // "I", "study" <-- array of removed elements
The splice method is also able to insert the elements without any removals. For that we need to set deleteCount to 0 :
1 let arr = ["I", "study", "JavaScript"];
2
3 // from index 2
4 // delete 0
5 // then insert "complex" and "language"
6 arr.splice(2, 0, "complex", "language");
7
8 alert( arr ); // "I", "study", "complex", "language", "JavaScript"
Negative indexes allowed
Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like
here:
1 let arr = [1, 2, 5];
2
3 // from index -1 (one step from the end)
4 // delete 0 elements,
5 // then insert 3 and 4
6 arr.splice(-1, 0, 3, 4);
7
8 alert( arr ); // 1,2,3,4,5
slice
1 arr.slice([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 str.slice , but instead of substrings it makes subarrays.
For instance:
1 let arr = ["t", "e", "s", "t"];
2
3 alert( arr.slice(1, 3) ); // e,s (copy from 1 to 3)
4
5 alert( arr.slice(-2) ); // s,t (copy from -2 till the end)
We can also call it without arguments: arr.slice() 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 arr.concat creates a new array that includes values from other arrays and additional items.
1 arr.concat(arg1, arg2...)
If an argument argN is an array, then all its elements are copied. Otherwise, the argument itself is copied.
For instance:
1 let arr = [1, 2];
2
3 // create an array from: arr and [3,4]
4 alert( arr.concat([3, 4]) ); // 1,2,3,4
5
6 // create an array from: arr and [3,4] and [5,6]
7 alert( arr.concat([3, 4], [5, 6]) ); // 1,2,3,4,5,6
8
9 // create an array from: arr and [3,4], then add values 5 and 6
10 alert( arr.concat([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:
1 let arr = [1, 2];
2
3 let arrayLike = {
4 0: "something",
5 length: 1
6 };
7
8 alert( arr.concat(arrayLike) ); // 1,2,[object Object]
…But if an array-like object has a special Symbol.isConcatSpreadable property, then it’s treated as an array by concat :
its elements are added instead:
1 let arr = [1, 2];
2
3 let arrayLike = {
4 0: "something",
5 1: "else",
6 [Symbol.isConcatSpreadable]: true,
7 length: 2
8 };
9
10 alert( arr.concat(arrayLike) ); // 1,2,something,else
Iterate: forEach
The arr.forEach method allows to run a function for every element of the array.
The syntax:
1 // for each element call alert
2 ["Bilbo", "Gandalf", "Nazgul"].forEach(alert);
And this code is more elaborate about their positions in the target array:
1 ["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => {
2 alert(`${item} is at index ${index} in ${array}`);
3 });
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 arr.indexOf and arr.includes have the similar syntax and do essentially the same as their string counterparts, but
operate on items instead of characters:
● arr.indexOf(item, from) – looks for item starting from index from , and returns the index where it was found,
otherwise -1 .
● arr.includes(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:
1 let arr = [1, 0, false];
2
3 alert( arr.indexOf(0) ); // 1
4 alert( arr.indexOf(false) ); // 2
5 alert( arr.indexOf(null) ); // -1
6
7 alert( arr.includes(1) ); // true
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 arr.includes is preferred.
The method arr.lastIndexOf is the same as indexOf , but looks for from right to left.
1 let fruits = ['Apple', 'Orange', 'Apple']
2
3 alert( fruits.indexOf('Apple') ); // 0 (first Apple)
4 alert( fruits.lastIndexOf('Apple') ); // 2 (last Apple)
1 const arr = [NaN];
2 alert( arr.indexOf(NaN) ); // -1 (wrong, should be 0)
3 alert( arr.includes(NaN) );// true (correct)
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 the 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 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 :
1 let users = [
2 {id: 1, name: "John"},
3 {id: 2, name: "Pete"},
4 {id: 3, name: "Mary"}
5 ];
6
7 let user = users.find(item => item.id == 1);
8
9 alert(user.name); // John
In real life arrays of objects is a common thing, so the find method is very useful.
Note that in the example we provide to find the function item => item.id == 1 with one argument. That’s typical,
other arguments of this function are rarely used.
The arr.findIndex 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 arr.findLastIndex method is like findIndex , but searches from right to left, similar to lastIndexOf .
Here’s an example:
1 let users = [
2 {id: 1, name: "John"},
3 {id: 2, name: "Pete"},
4 {id: 3, name: "Mary"},
5 {id: 4, name: "John"}
6 ];
7
8 // Find the index of the first John
9 alert(users.findIndex(user => user.name == 'John')); // 0
10
11 // Find the index of the last John
12 alert(users.findLastIndex(user => user.name == 'John')); // 3
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:
For instance:
1 let users = [
2 {id: 1, name: "John"},
3 {id: 2, name: "Pete"},
4 {id: 3, name: "Mary"}
5 ];
6
7 // returns array of the first two users
8 let someUsers = users.filter(item => item.id < 3);
9
10 alert(someUsers.length); // 2
Transform an array
Let’s move on to methods that transform and reorder an array.
map
The arr.map 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.
1 let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length);
2 alert(lengths); // 5,7,6
sort(fn)
The call to arr.sort() 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:
1 let arr = [ 1, 2, 15 ];
2
3 // the method reorders the content of arr
4 arr.sort();
5
6 alert( arr ); // 1, 15, 2
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 arr.sort() .
1 function compare(a, b) {
2 if (a > b) return 1; // if the first value is greater than the second
3 if (a == b) return 0; // if values are equal
4 if (a < b) return -1; // if the first value is less than the second
5 }
1 function compareNumeric(a, b) {
2 if (a > b) return 1;
3 if (a == b) return 0;
4 if (a < b) return -1;
5 }
6
7 let arr = [ 1, 2, 15 ];
8
9 arr.sort(compareNumeric);
10
11 alert(arr); // 1, 2, 15
Let’s step aside and think what’s happening. The arr can be 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 arr.sort(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 from alerting them:
1 [1, -2, 15, 2, 0, 8].sort(function(a, b) {
2 alert( a + " <> " + b );
3 return a - b;
4 });
The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as
possible.
1 let arr = [ 1, 2, 15 ];
2
3 arr.sort(function(a, b) { return a - b; });
4
5 alert(arr); // 1, 2, 15
Arrow functions for the best
Remember arrow functions? We can use them here for neater sorting:
For many alphabets, it’s better to use str.localeCompare method to correctly sort letters, such as Ö .
1 let countries = ['Österreich', 'Andorra', 'Vietnam'];
2
3 alert( countries.sort( (a, b) => a > b ? 1 : -1) ); // Andorra, Vietnam, Österreich
4
5 alert( countries.sort( (a, b) => a.localeCompare(b) ) ); // Andorra,Österreich,Vietn
reverse
For instance:
1 let arr = [1, 2, 3, 4, 5];
2 arr.reverse();
3
4 alert( arr ); // 5,4,3,2,1
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 str.split(delim) method does exactly that. It splits the string into an array by the given delimiter delim .
1 let names = 'Bilbo, Gandalf, Nazgul';
2
3 let arr = names.split(', ');
4
5 for (let name of arr) {
6 alert( `A message to ${name}.` ); // A message to Bilbo (and other names)
7 }
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:
1 let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2);
2
3 alert(arr); // Bilbo, Gandalf
1 let str = "test";
2
3 alert( str.split('') ); // t,e,s,t
The call arr.join(glue) does the reverse to split . It creates a string of arr items joined by glue between them.
For instance:
1 let arr = ['Bilbo', 'Gandalf', 'Nazgul'];
2
3 let str = arr.join(';'); // glue the array into a string using ;
4
5 alert( str ); // 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 arr.reduce and arr.reduceRight 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 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?
1 let arr = [1, 2, 3, 4, 5];
2
3 let result = arr.reduce((sum, current) => sum + current, 0);
4
5 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…
1 2 3 4 5 0+1+2+3+4+5 = 15
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.
We also can omit the initial value:
1 let arr = [1, 2, 3, 4, 5];
2
3 // removed initial value from reduce (no 0)
4 let result = arr.reduce((sum, current) => sum + current);
5
6 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:
1 let arr = [];
2
3 // Error: Reduce of empty array with no initial value
4 // if the initial value existed, reduce would return it for the empty arr.
5 arr.reduce((sum, current) => sum + current);
The method arr.reduceRight does the same, but goes from right to left.
Array.isArray
Arrays do not form a separate language type. They are based on objects.
1 alert(typeof {}); // object
2 alert(typeof []); // object (same)
…But arrays are used so often that there’s a special method for that: Array.isArray(value). It returns true if the value is an
array, and false otherwise.
1 alert(Array.isArray({})); // false
2
3 alert(Array.isArray([])); // true
That parameter is not explained in the sections above, because it’s rarely used. But for completeness we have to cover it.
Here’s the full syntax of these methods:
1 arr.find(func, thisArg);
2 arr.filter(func, thisArg);
3 arr.map(func, thisArg);
4 // ...
5 // thisArg is the optional last argument
For example, here we use a method of army object as a filter, and thisArg passes the context:
1 let army = {
2 minAge: 18,
3 maxAge: 27,
4 canJoin(user) {
5 return user.age >= this.minAge && user.age < this.maxAge;
6 }
7 };
8
9 let users = [
10 {age: 16},
11 {age: 20},
12 {age: 23},
13 {age: 30}
14 ];
15
16 // find users, for who army.canJoin returns true
17 let soldiers = users.filter(army.canJoin, army);
18
19 alert(soldiers.length); // 2
20 alert(soldiers[0].age); // 20
21 alert(soldiers[1].age); // 23
If in the example above we used users.filter(army.canJoin) , then army.canJoin would be called as a standalone
function, with this=undefined , thus leading to an instant error.
Summary
A cheat sheet of array methods:
● To add/remove elements:
● indexOf/lastIndexOf(item, pos) – look for item starting from position pos , 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.
● To iterate over elements:
● forEach(func) – calls func for every element, does not return anything.
● To transform the array:
● 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:
● Array.isArray(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, arr.some() immediately returns
true and stops iterating over the rest of items; if fn returns a falsy value, arr.every() immediately returns false
and stops iterating over the rest of items as well.
1 function arraysEqual(arr1, arr2) {
2 return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[i
3 }
4
5 alert( arraysEqual([1, 2], [1, 2])); // true
● arr.fill(value, start, end) – fills the array with repeating value from index start to end .
● arr.copyWithin(target, start, end) – copies its elements from position start till position end into itself, at position
target (overwrites existing).
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
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:
1 camelize("background-color") == 'backgroundColor';
2 camelize("list-style-image") == 'listStyleImage';
3 camelize("-webkit-transition") == 'WebkitTransition';
P.S. Hint: use split to split the string into an array, transform it and join back.
solution
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:
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:
solution
importance: 4
solution
importance: 5
We have an array of strings arr . We’d like to have a sorted copy of it, but keep arr unmodified.
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:
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.
solution
Map to names
importance: 5
You have an array of user objects, each one has user.name . Write the code that converts it into an array of names.
For instance:
1 let john = { name: "John", age: 25 };
2 let pete = { name: "Pete", age: 30 };
3 let mary = { name: "Mary", age: 28 };
4
5 let users = [ john, pete, mary ];
6
7 let names = /* ... your code */
8
9 alert( names ); // John, Pete, Mary
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:
So, actually you need to map one array of objects to another. Try using => here. There’s a small catch.
solution
importance: 5
Write the function sortByAge(users) that gets an array of objects with the age property and sorts them by age .
For instance:
solution
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:
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
importance: 4
Write the function getAverageAge(users) that gets an array of objects with property age and returns the average age.
For instance:
1 let john = { name: "John", age: 25 };
2 let pete = { name: "Pete", age: 30 };
3 let mary = { name: "Mary", age: 29 };
4
5 let arr = [ john, pete, mary ];
6
7 alert( getAverageAge(arr) ); // (25 + 30 + 29) / 3 = 28
solution
importance: 4
Create a function unique(arr) that should return an array with unique items of arr .
For instance:
1 function unique(arr) {
2 /* your code */
3 }
4
5 let strings = ["Hare", "Krishna", "Hare", "Krishna",
6 "Krishna", "Krishna", "Hare", "Hare", ":-O"
7 ];
8
9 alert( unique(strings) ); // Hare, Krishna, :-O
solution
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:
1 let users = [
2 {id: 'john', name: "John Smith", age: 20},
3 {id: 'ann', name: "Ann Smith", age: 24},
4 {id: 'pete', name: "Pete Peterson", age: 31},
5 ];
6
7 let usersById = groupById(users);
8
9 /*
10 // after the call we should have:
11
12 usersById = {
13 john: {id: 'john', name: "John Smith", age: 20},
14 ann: {id: 'ann', name: "Ann Smith", age: 24},
15 pete: {id: 'pete', name: "Pete Peterson", age: 31},
16 }
17 */
In this task we assume that id is unique. There may be no two array items with the same id .
Comments
● 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…)