index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Сортировка */
  2. var persons = [
  3. {name: "Иван", age: 17},
  4. {name: "Мария", age: 35},
  5. {name: "Алексей", age: 73},
  6. {name: "Яков", age: 12},
  7. ]
  8. function sort(array, field, order = true) {
  9. let arrSorted = array.sort(function (a, b){
  10. if (a[field] > b[field]) {
  11. return order ? 1 : -1;
  12. }
  13. else{
  14. return order ? -1 : 1;
  15. }
  16. })
  17. return arrSorted
  18. }
  19. sort(persons, 'age', false)
  20. /* array map */
  21. let arr = ["1", {}, null, undefined, "500", 700]
  22. let arr1 = arr.map(x => typeof x === 'string' ? +x : x)
  23. console.log(arr1)
  24. /* array reduce */
  25. let arr2 = ["0", 5, 3, "string", null];
  26. let arr3 = arr2.filter(x => typeof x === 'number').reduce((a, b) => a *= b)
  27. console.log(arr3)
  28. /* object filter */
  29. var phone = {
  30. brand: "meizu",
  31. model: "m2",
  32. ram: 2,
  33. color: "black",
  34. };
  35. filter(phone, (key, value) => key == "color" || value == 2);
  36. function filter(obj, validator) {
  37. let object = {};
  38. for (let key in obj) {
  39. if (validator(key, obj[key])) {
  40. object[key] = obj[key];
  41. }
  42. }
  43. return object;
  44. }
  45. /* object map */
  46. map({name: "Иван", age: 17},function(key,value){
  47. var result = {};
  48. result[key+"_"] = value + "$";
  49. return result;
  50. })
  51. function map(obj, validator) {
  52. let object = {}
  53. for (key in obj) {
  54. object = {...object, ...validator(key, obj[key])}
  55. }
  56. return object
  57. }
  58. /* Рекурсия: sum */
  59. function progression(n) {
  60. if (n === 0) {
  61. return 0
  62. } else {
  63. return n + progression(n - 1)
  64. }
  65. }