index.html 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. //map и filter создают новый массив
  12. // sort //1
  13. let persons = [
  14. { name: "Иван", age: 17 },
  15. { name: "Мария", age: 35 },
  16. { name: "Алексей", age: 73 },
  17. { name: "Яков", age: 12 },
  18. { name: "А", age: 1 },
  19. { name: "Б", age: 5 },
  20. { name: "В", age: 3 },
  21. { name: "Г", age: 7 },
  22. ]
  23. function sort(array, keyName, reverse) {
  24. if (keyName === "age") {
  25. array.sort((a, b) => parseFloat(a.age) - parseFloat(b.age))
  26. if (reverse === false) {
  27. array.sort((a, b) => parseFloat(b.age) - parseFloat(a.age))
  28. }
  29. console.log(array);
  30. }
  31. else if (keyName === "name") {
  32. array.sort((a, b) => a.name.localeCompare(b.name))
  33. if (reverse === false) {
  34. array.sort((a, b) => b.name.localeCompare(a.name))
  35. }
  36. console.log(array);
  37. }
  38. }
  39. // array map //
  40. function returnInt(element) {
  41. if (typeof element === "string") {
  42. return parseInt(element, 10);
  43. } else {
  44. return element;
  45. }
  46. }
  47. console.log(["1", {}, null, undefined, "500", 700].map(returnInt))
  48. // array reduce //
  49. function reducer(accumulator, currentValue) {
  50. if (typeof currentValue === "number") {
  51. return accumulator *= currentValue;
  52. };
  53. return accumulator
  54. }
  55. console.log(`array reduce = ${["0", 5, 3, "string", null].reduce(reducer, 1)}`); //единица задается 1му элементу
  56. // object filter //
  57. var phone = {
  58. brand: "meizu",
  59. model: "m2",
  60. ram: 2,
  61. color: "black",
  62. }
  63. // function filter(obj, func) {
  64. // obj.key
  65. // }
  66. function filter(obj, func) {
  67. return Object.entries(obj).filter(e => func(...e)).reduce((a, [b, c] = b) => (a[b] = c, a), {})
  68. }
  69. console.log(filter(phone, (key, value) => key == "color" || value == 2))
  70. // object map //
  71. function map(obj, func) {
  72. var object = {};
  73. for (var key in obj) {
  74. Object.assign(object, func(key, object[key])), delete object[key];;
  75. }
  76. return object;
  77. }
  78. //почему то undefind выдает
  79. console.log(map({ name: "Иван", age: 17 }, function (key, value) {
  80. var result = {};
  81. result[key + "_"] = value + "$";
  82. return result;
  83. }))
  84. </script>
  85. </body>
  86. </html>