123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- // sort
- var persons = [
- { name: "Иван", age: 17 },
- { name: "Мария", age: 35 },
- { name: "Алексей", age: 73 },
- { name: "Яков", age: 12 },
- ]
- function sort(persons, key, ok = true) {
- return persons.sort((a, b) => {
- let result;
- if (ok) { result = a[key] > b[key] ? 1 : -1; }
- else { result = a[key] < b[key] ? 1 : -1; }
- return result;
- })
- }
- console.log(sort(persons, "age"));
- ///////////////////////////////////////////////
- console.log(sort(persons, "name", false));
- ///////////////////////////////////////////////
- console.log(sort(persons, "name"));
- // array map
- var numbers = ["1", {}, null, undefined, "500", 700].map(function (a) { if ((+a) > 0) return +a; else return a })
- console.log(numbers)
- // array reduce
- let number01 = ["0", 5, 3, "string", null];
- let number02 = number01.filter(item => typeof item === 'number').reduce((a, b) => a * b)
- console.log(number02)
- // object filter
- var phone = {
- brand: "meizu",
- model: "m2",
- ram: 2,
- color: "black",
- };
- function filter(object, callback) {
- let filterPhone = {}
- for (let key in object) {
- if (callback(key, object[key]))
- filterPhone = { ...filterPhone, [key]: object[key] };
- }
- return filterPhone;
- }
- console.log(filter(phone, (key, value) => key == "color" || value == 2));
- // object map
- function objectMap(object, callback) {
- let filter = {}
- for (let key in object) {
- filter = { ...filter, ...callback([key], object[key]) };
- }
- return filter;
- }
- let finish = objectMap({ name: "Иван", age: 17 }, function (key, value) {
- var result = {};
- result[key + "_"] = value + "$";
- return result;
- })
- console.log(finish)
- // Рекурсия
- // Sum
- let fact = n => n <= 0 ? 0 : n + fact(n - 1);
- console.log(fact(0))
- console.log(fact(1))
- console.log(fact(3))
- console.log(fact(5))
- console.log(fact(7))
- console.log(fact(9))
|