Use map () when: you need to translate / map all elements in an array to another set of values.
Example: convert temperature from Fahrenheit 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:
traverses the array from left to right by invoking a return function on each element with parameters.
For each callback, the return value becomes the element of the new array.
After all the elements have been traversed, map () returns the new array with all the "translated" elements.
sort ()
The sort () method allows your scripts to sort entries in an array by almost every kind of criteria that you can associate with an entry.
For entries consisting of strings, the criteria can be your alphabetical order, string size, etc. eg
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 numeric entries, the criterion can be your numerical order.
First look at the type of classification you can do with the sort()
method in isolation (for example without calling a comparison function). When none of the parameters is specified, javascript takes a snapshot of the contents of the array and converts the items to strings. From there, it performs a classification of strings of the values. The ASCII values of characters control sorting, which means that numbers are sorted by their string values, not their numeric values. This fact has strong implications if your array consists of numeric data: value 201 comes before 88 because the sort engine compares the first string characters ("2" with "8") to determine the sort order. / p>
Fortunately, there is additional intelligence that you can include in the array sort. The main tactic is to define a function that will help the sort()
method compare array items. A comparison function receives two values from the array (what you do not see is that the sort()
method quickly sends multiple pairs of array values to help you sort all entries). The comparison function allows the sort()
method to know which of the two items comes before the other, based on the value that the function returns. Assuming the function compares two values, a e b
, the returned value reveals information for the sort()
method, 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 numeric values. To sort the items in numerical order, you define a comparison function, which is called from the sort()
method. Note that, unlike calling other functions, the% method parameter uses a reference to the function without the parentheses.
Whenever sort()
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 compare()
and a
. If a is greater than b, then a positive value returns the b
method, saying to keep sort()
after a
(that is, position b
in an index location with value greater than a
) . On the other hand, if b
is less than a
, then the negative value says sort () to set b
to a point with index value less than a
.
Sample result:
myArray = new Array(12, 5, 200, 80)
function compare(a,b) {
return a-b
}
console.log(myArray.sort(compare));
Source: JavaScript the Danny Goodman Bible