Use map() when: you need to translate/map all elements in one array to another set of values.
Example: convert Fahrenheit temperature to Celsius.
var fahrenheit = [ 0, 23, 45, 55, 85, 90, 100, 150, 200 ];
var celcius = fahrenheit.map( function( elem ) {
return Math.round( ( elem - 32 ) * 5 / 9 );
} );
console.log(celcius);
What map() does:
traverse the array from left to right by invoking a return function on each element with parameters.
For each return call, the returned value becomes the element of the new array.
After all elements have been traversed, map() returns the new array with all "translated" elements.
Sort()
The Sort() method allows your scripts to classify array entries by almost every kind of criteria you can associate with an entry.
For entries consisting of strings, the criterion can be their alphabetical order, string size etc.. as for example:
solarSys = new Array(9)
solarSys[0] = "Mercurio"
solarSys[1] = "Venus"
solarSys[2] = "Terra"
solarSys[3] = "Marte"
solarSys[4] = "Jupiter"
solarSys[5] = "Saturno"
solarSys[6] = "Urano"
solarSys[7] = "Netuno"
solarSys[8] = "Plutão"
// comparison functions
function compare1(a,b) {
// ordem alfabética decrescente
if (a > b) {return -1}
if (b > a) {return 1}
return 0
}
function compare2(a,b) {
// último caractere dos nomes dos planetas
var aComp = a.charAt(a.length - 1)
var bComp = b.charAt(b.length - 1)
if (aComp < bComp) {return -1}
if (aComp > bComp) {return 1}
return 0
}
function compare3(a,b) {
// tamanho dos nomes dos planetas
return a.length - b.length
}
// comparar e exibir matriz
function sortIt(form, compFunc) {
var delimiter = ";"
if (compFunc == null) {
solarSys.sort()
} else {
solarSys.sort(compFunc)
}
// display results in field
form.output.value = unescape(solarSys.join(delimiter))
}
Este documento contém uma matriz de planetas em nosso sistema solar.
<FORM>
<p>Clique em um botão para ordenar a matriz:<P>
<INPUT TYPE="button" VALUE="Alfabetica A-Z" onClick="sortIt(this.form)">
<INPUT TYPE="button" VALUE="Alfabetica Z-A" onClick="sortIt(this.form,compare1)">
<INPUT TYPE="button" VALUE="Ultimo Caractere" onClick="sortIt(this.form,compare2)">
<INPUT TYPE="button" VALUE="Tamanho do nome" onClick="sortIt(this.form,compare3)">
<INPUT TYPE="button" VALUE="Reset" onClick="self.location.reload()">
<INPUT TYPE="text" NAME="output" SIZE=62>
</TEXTAREA>
</FORM>
For numerical entries, the criterion can be their numerical order.
First see the type of rating you can do with the method sort()
separately (for example without calling a comparison function). When none of the parameters are specified, javascript takes a snapshot of the contents of the array and converts the items into strings. From there, it performs a string classification of the values. The ASCII values of the characters control the classification, meaning that the numbers are classified by their string values, not their numerical values. This fact has strong implications if its array consists of numerical data: the value 201 comes before 88, because the sorting mechanism compares the first string characters ("2" to "8") to determine the sorting order.
Fortunately, there is additional intelligence that you can include in the array classification. The main tactic is to define a function that helps the method sort()
to compare array items. A comparison function receives two array values (what you don’t see is that method sort()
quickly sends several pairs of array values to help you sort all entries). The comparison function allows the method sort()
know which of the two items comes before the other, based on the value the function returns. Assuming the function compares two values, a e b
, the returned value reveals information for the method sort()
, as shown below:
intervalo do valor de retorno significado
< 0 Valor `b` deve vir depois de `a`
0 A ordem de a e b não deve mudar
> 0 Valor `a` deve vir depois de `b`
Imagine the following example:
myArray = new Array(12, 5, 200, 80)
function compare(a,b) {
return a-b
}
myArray.sort(compare)
The array has four numerical values. To sort the items in numerical order, you define a comparison function, which is called from the method sort()
. Note that, unlike the call of other functions, the method parameter sort()
uses a reference to the function without parentheses.
Every time compare()
is called, Javascript assigns two of the array values to the parameter variables (a and b). In the previous example, the value returned is the difference between a
and b
. If a is greater than b, then a positive value returns to the method sort()
, telling to keep a
after b
(that is, position a
at an index location greater than b
). On the other hand, if a
is less than b
, then the negative value tells Sort() to put a
at a point with an index value less than b
.
Example result:
myArray = new Array(12, 5, 200, 80)
function compare(a,b) {
return a-b
}
console.log(myArray.sort(compare));
Source: Javascript Danny Goodman’s Bible
thanks for the explanation, great!
– user3262051