script.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //-----------------------------------------------------------sort---------------------------------------------------------------------------
  2. var persons = [{
  3. name: "Иван",
  4. age: 17
  5. },
  6. {
  7. name: "Мария",
  8. age: 35
  9. },
  10. {
  11. name: "Алексей",
  12. age: 73
  13. },
  14. {
  15. name: "Яков",
  16. age: 12
  17. },
  18. ]
  19. function sort(array, key, increase = true) {
  20. if (increase) {
  21. array.sort(function (a, b) {
  22. if (a[key] > b[key]) {
  23. return 1;
  24. }
  25. if (a[key] < b[key]) {
  26. return -1;
  27. }
  28. return 0;
  29. });
  30. } else {
  31. array.sort(function (a, b) {
  32. if (a[key] < b[key]) {
  33. return 1;
  34. }
  35. if (a[key] > b[key]) {
  36. return -1;
  37. }
  38. return 0;
  39. });
  40. }
  41. return array;
  42. };
  43. // console.log(sort(persons, "age")); //сортирует по возрасту по возрастанию
  44. // console.log(sort(persons, "name"));
  45. // console.log(sort(persons, "age", true));
  46. // console.log(sort(persons, "name", true));
  47. // console.log(sort(persons, "name", false)); //сортирует по имени по убыванию
  48. // console.log(sort(persons, "age", false)); //сортирует по имени по убыванию
  49. //-----------------------------------------------------------array map----------------------------------------------------------------------
  50. let arrayMap = ["1", {}, null, undefined, "500", 700];
  51. let arrayMap2 = arrayMap.map((item) => {
  52. if (typeof item == "string") return isNaN(parseInt(item, 10)) ? item : parseInt(item, 10);
  53. return item;
  54. });
  55. // console.log(arrayMap2);
  56. //-----------------------------------------------------------array reduce--------------------------------------------------------------------
  57. let arrayReduce = ["0", 5, 3, "string", null];
  58. let arrayPow = arrayReduce.reduce((a, b) => (typeof b == "number" ? a * b : a), 1);
  59. console.log(arrayPow);
  60. //-----------------------------------------------------------object filter--------------------------------------------------------------------
  61. var phone = {
  62. brand: "meizu",
  63. model: "m2",
  64. ram: 2,
  65. color: "black",
  66. };
  67. function filter(obj) {
  68. let obj2 = {};
  69. for (let key in obj) {
  70. if (key == "color" || obj[key] == 2) {
  71. obj2[key] = obj[key];
  72. }
  73. }
  74. return obj2;
  75. }
  76. console.log(filter(phone));
  77. //-----------------------------------------------------------object map--------------------------------------------------------------------