3.2 - sortByField() - v1.1

Усовершенствовать функцию sortByField() из первого задания следующим образом: название поля теперь может содержать символ "+" (сортировать по возрастанию) или "-" (по убыванию). Например, sortByField(a, "-age") сортирует массив по убыванию поля age. Если направление не указано, сортировать по возрастанию

by l_gordienkova

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.min.css">
<div id="mocha">
</div>
<script>
  mocha.setup('bdd');
  var assert = chai.assert;
  var expect = chai.expect;
</script>
<script>

  describe("sortByField - v 1.1 (с направлением)", function() {
  	var data;
    function pick(){
    	return Array.prototype.map.call(arguments, x => data[x]);
    }
    before(function () {
      function person(name, surname, age, year, month, day, wealth){
      	return {
        	name: name,
          surname: surname,
          age: age,
          birth:{
          	year: year,
            month: month,
            day: day
          },
          wealth: wealth
        };
      }
      data = [
      	person("Bill", "Gates",				60, 1955, 10, 25, 77.6),	//0
      	person("Warren", "Buffett",		85, 1930, 08, 30, 67.3),	//1
      	person("Jeff", "Bezos",				52, 1964, 01, 12, 52.3),	//2
      	person("Larry", "Ellison",		71, 1944, 08, 17, 50.1),	//3
      	person("Mark", "Zuckerberg",	33, 1984, 05, 14, 49.1),	//4
      	person("Michael", "Bloomberg",74, 1942, 02, 14, 43.7),	//5
      	person("Charles", "Koch",			80, 1935, 11, 01, 43),		//6
      	person("David", "Koch",				60, 1956, 03, 07, 43),		//7
      	person("Larry", "Page",				60, 1973, 03, 26, 37.8),	//8
      	person("Sergey", "Brin",			42, 1973, 08, 21, 36.9),	//9
      	person("Jim", "Walton",				67, 1948, 06, 07, 34.8),	//10
      	person("Alice", "Walton",			66, 1949, 10, 07, 33.5),	//11
      	person("S. Robson", "Walton",	71, 1944, 10, 28, 33.1),	//12
      	person("Sheldon", "Adelson",	82, 1933, 08, 06, 28),		//13
      	person("Forrest Jr.", "Mars",	84, 1931, 08, 16, 25.8),	//14
      	person("Jacqueline", "Mars",	76, 1939, 10, 10, 25.8),	//15
      	person("John", "Mars",				80, 1935, 10, 15,...

JavaScript

function sortByField(a, field){


if(field.charAt(0) == '-'){

	 return a.sort(function(b,c){
   
			if (b[field.substr(1)] > c[field.substr(1)]) {
	    	return -1;
	  }
	   else  return 1;
		});
}


if(field.charAt(0) == '+'){

	return a.sort(function(b,c){
		if (b[field.substr(1)] > c[field.substr(1)]) {
	    return 1;
	  }
	   else return -1;
		});
}


if(field.charAt(0) !== '-' && field.charAt(0) !== '+' ){
	return a.sort(function(b,c){
			if (b[field] > c[field]) {
	    return 1;
	  }
	else  return -1;
		});
}

}