When using the sort () or map () method,

2

According to the MDN:

sort() changes the original array, if using a functional approach the comparison function can be invoked several times, and can cause execution of processing. The more work the Comparison function does, and the more elements there are to sort would be Legal consider using a map to sort.

I would like an example in a real case that I could replace sort() with map() , in which situation I use map() instead of sort (), does it actually impact performance?

and what is the difference using a - b and a > b if both have the same goal to sort

    
asked by anonymous 30.05.2017 / 00:20

2 answers

3

The .map() does not serve to sort, but rather 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, map did not perform sorting, only transforming a array into another.

On the other hand, sort does to the ordering of the elements, for that uses comparison function, which must receive two values and return a number.

  • If you receive A and B return a number less than 0, then B must appear before A .
  • If you get A and B return 0, then B and A should keep your current order (but this behavior is not guaranteed).
  • If you receive A and B return a number greater than 0, then A must appear before B .

In this case it matters little whether the function returns -1 or -65535 , the comparison function does not look at the number's magnitude, only if it is greater or less than 0.

Let's take 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 sorting 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 sort 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);

So you can use any type of object, which has an appropriate comparison function for the desired ordering, below is a sort order 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);

Finally, you can combine sort and 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);
    
30.05.2017 / 01:40
2

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

    
30.05.2017 / 02:11