123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- //map и filter создают новый массив
- // sort //1
- let persons = [
- { name: "Иван", age: 17 },
- { name: "Мария", age: 35 },
- { name: "Алексей", age: 73 },
- { name: "Яков", age: 12 },
- { name: "А", age: 1 },
- { name: "Б", age: 5 },
- { name: "В", age: 3 },
- { name: "Г", age: 7 },
- ]
- function sort(array, keyName, reverse) {
- if (keyName === "age") {
- array.sort((a, b) => parseFloat(a.age) - parseFloat(b.age))
- if (reverse === false) {
- array.sort((a, b) => parseFloat(b.age) - parseFloat(a.age))
- }
- console.log(array);
- }
- else if (keyName === "name") {
- array.sort((a, b) => a.name.localeCompare(b.name))
- if (reverse === false) {
- array.sort((a, b) => b.name.localeCompare(a.name))
- }
- console.log(array);
- }
- }
- // array map //
- function returnInt(element) {
- if (typeof element === "string") {
- return parseInt(element, 10);
- } else {
- return element;
- }
- }
- console.log(["1", {}, null, undefined, "500", 700].map(returnInt))
- // array reduce //
- function reducer(accumulator, currentValue) {
- if (typeof currentValue === "number") {
- return accumulator *= currentValue;
- };
- return accumulator
- }
- console.log(`array reduce = ${["0", 5, 3, "string", null].reduce(reducer, 1)}`); //единица задается 1му элементу
- // object filter //
- var phone = {
- brand: "meizu",
- model: "m2",
- ram: 2,
- color: "black",
- }
- // function filter(obj, func) {
- // obj.key
- // }
- function filter(obj, func) {
- return Object.entries(obj).filter(e => func(...e)).reduce((a, [b, c] = b) => (a[b] = c, a), {})
- }
- console.log(filter(phone, (key, value) => key == "color" || value == 2))
- // object map //
- function map(obj, func) {
- var object = {};
- for (var key in obj) {
- Object.assign(object, func(key, object[key])), delete object[key];;
- }
- return object;
- }
- //почему то undefind выдает
- console.log(map({ name: "Иван", age: 17 }, function (key, value) {
- var result = {};
- result[key + "_"] = value + "$";
- return result;
- }))
- </script>
- </body>
- </html>
|