When using the Sort() or map() method

Asked

Viewed 831 times

2

According to the MDN:

the sort() changes the original array, if it is using a functional approach the comparison function can be invoked several times, and can cause processing execess. The more work workDeparacode to do, and the more elements there are to sort it would be nice to consider using a map to sort.

would like an example in a real case that I could replace the sort() for map(), in which situation I use the map() in place of Sort(), really impacts on performance?

and what is the difference using a - b and a > b if the two have the same goal to ordain

2 answers

4

The .map() not to sort, but to map one entity to another.

let Pessoa1 = function (nome, sobrenome) {
  this.nome = nome;
  this.sobrenome = sobrenome;
}

let Pessoa2 = function (nome, email) {
  this.nome = nome;
  this.email = email;
}

let pessoas1 = [
  new Pessoa1("Nome1", "Sobrenome1"),
  new Pessoa1("Nome2", "Sobrenome2"),
  new Pessoa1("Nome3", "Sobrenome3"),
  new Pessoa1("Nome4", "Sobrenome4")
];

let pessoas2 = pessoas1.map(function (pessoa1) {
  let nome = pessoa1.nome + " " + pessoa1.sobrenome;
  let email = nome.toLowerCase().replace(" ", ".") + "@stack.com";
  return new Pessoa2(nome, email);
});

console.log(pessoas2);

As you can see above, the map did not carry out the ordination, only the transformation of a array in another.

on the other hand, the sort does the ordering of the elements, for this use comparison function, which must receive two values and return a number.

  • If on receiving A and B return a number less than 0, then B should appear before A.
  • If on receiving A and B return 0, then B and A should maintain to their current order (however this behavior is not guaranteed).
  • If on receiving A and B return a number greater than 0, then A should appear before B.

In this case it doesn’t matter if the function returns -1 or -65535, the comparison function does not look at the quantity of the number, only if it is greater than or less than 0.

let’s go to an example with words.

var frutas = [ 'Laranja', 'Banana', 'Maça' ];
frutas.sort(function (frutaA, frutaB) {
  if (frutaA == frutaB)
    return 0;
  if (frutaA < frutaB)
    return -1
  if (frutaA > frutaB)
    return 1
});
// ordenada por ordem alfabetica.
console.log(frutas);

but this all depends on your ordering criteria.:

var frutas = [ 'Laranja', 'Banana', 'Maça' ];
frutas.sort(function (frutaA, frutaB) {
  if (frutaA.length == frutaB.length)
    return 0;
  if (frutaA.length < frutaB.length)
    return -1
  if (frutaA.length > frutaB.length)
    return 1
});

console.log(frutas);

of course, the above ordering uses numbers, so it can be simplified to.:

var frutas = [ 'Laranja', 'Banana', 'Maça' ];
frutas.sort(function (frutaA, frutaB) {
  return frutaA.length - frutaB.length;
});

console.log(frutas);

Then, you can use whatever type of object, since it has an appropriate comparison function for the desired ordering, below follows an ordering with dates.:

var datas = [ 
  new Date(1990, 1, 12), 
  new Date(1985, 25, 1), 
  new Date(1990, 1, 10) 
];
datas.sort(function (dataA, dataB) {
  return dataA.getTime() - dataB.getTime();
});

console.log(datas);

and finally, you can come to combine the sort and the map

var datas = [ 
  new Date(1990, 1, 12), 
  new Date(1985, 25, 1), 
  new Date(1990, 1, 10) 
];
datas = datas.sort(function (dataA, dataB) {
  return dataA.getTime() - dataB.getTime();
}).map(function (data) {
  return data.toLocaleDateString("pt-BR");
});

console.log(datas);

  • thanks for the explanation, great!

2

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

  • thank you! excellent explanation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.