A short summary of the most commonly used array methods available in JavaScript
forEach()
is an async method (while normal for
loops aren’t).
iterates over every element of the array, creating a new array with values that have been modified by the callback function , and returns. It does not modify the original array.
1var newArray = oldArray.map(function(val){
2 return val + 3;
3});
short answer: .forEach
modifies original array, .map
doesn’t.
It’s this simple:
.map
returns a new array, whereas.forEach
doesn’t return anything. Basically, if you want to obtain a modified form of the previous array, you use.map
, if you don’t want that, you use.forEach
- stackoverflow
foreach
iterates over a list and applies some operation with side effects to each list member (such as saving each one to the database for example)
map
iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (such as converting a list of strings to uppercase)
link
Favor `map()` over `forEach()` when you can. Avoid side-effects.#functional #JavaScript
— Eric Elliott (@_ericelliott) October 17, 2015
.forEach()
doesn’t return an array. In other words, .forEach()
terminates chains, while .map()
allows you to chain even more calls.
link
1var arr = [1, 3, 2];
2
3console.log(
4 // This one works:
5 arr
6 .map(function (i) {
7 return i + i;
8 })
9 // Chaining!
10 .sort()
11);
12// => [ 2, 4, 6 ]
13
14console.log(
15 // This one does not:
16 arr
17 .forEach(function (i) {
18 return i + i;
19 })
20 // This is where forEach breaks:
21 .sort()
22);
23// => TypeError: Cannot read property 'sort' of undefined
iterates through the array elements and condenses them into one value. e.g: arr = [4,5,6,7,8] will become 30 if you use .reduce
and add all the values.
1var array = [4,5,6,7,8];
2var singleVal = 0;
3
4singleVal = array.reduce(function(previousVal, currentVal){
5 return previousVal + currentVal;
6}, 0);
iterates through an array and filters out elements when a condition is not true. Any array element for which the callback returns true will be kept and elements that return false will be filtered out. e.g:
1array = array.filter(function(val) {
2 return val !== 5
3})
will give all values that are not 5.
sorts array elemnets alphabetically or numericaly. .sort()
sorts array elements in place and returns the sorted array.
If no callback, it converts values to strings and sorts alphabetically
sort can be passed a compare function as a callback. The compare function should return a negative number if a
should be before b
, a positive number if a
should be after b
, or 0
if they are equal.
1var array = [1, 12, 21, 2]
2array.sort(function(a, b) {
3 return a - b
4})
merges the contents of two arrays into one. takes an array as arg and returns a new array with the contents of this array added to the end
1newArray = oldArray.concat(concatMe)
takes an index value and chops the array at that index value from the beginning of array. if you give a negative value, it’ll slice from the end.
Takes a begin value and an (optional) end value. If begin is undefined, slice begins from index 0.
splits a string into an array. takes an arg and splits the array at the points where it is found. e.g:
1array = string.split(' ')
will split a sentence into words by breaking at the spaces.
str.split('');
commas without any spaces will break down individual letters/characters
operates the same way as .split()
achieves the opposite. e.g: Your array has days of the weeks, you can use .join()
to get them all in one sentence, like so:
1arr.join(', ')
.substr()
vs .substring()
vs. slice()
The difference is in the second argument. The second argument to substring is the index to stop at (but not include), but the second argument to substr is the maximum length to return. You can remember substring takes indices, as does yet another string extraction method, slice.
.indexOf()
Searches an array for elements. If not found, returns -1
. If found, returns the element’s index position. When writing conditionals, you can see if the returned value is > 1
to check if it exits.
String.indexOf
vs. Array.indexOf
The string method looks for a substring and the array method for an element.