数组对象相同数据进行分类 算法

参考:https://blog.csdn.net/qq_41547882/article/details/113929220

数组总最小值


<!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>
        // let arr = [9980, 998, 499, 198, 99, 50, 30, 20, 10];
        // let arr1 = [1, 1, 5, 7, 13, 5, 15, 13, 11, 46];

        let arr = [9980, 2000, 998, 499, 198, 99, 50, 30, 20, 10];
        let arr1 = [1, 1, 5, 7, 13, 5, 15, 13, 11, 46];


        function sum(arr, arr1) {
            let result = [];
            let combination = []

            for (let i = 0; i < arr.length; i++) {
                for (let j = 0; j < arr1.length; j++) {
                    combination.push({
                        arr: arr[i],
                        arr1: arr1[j],
                        value: arr[i] * arr1[j] - 9980
                    })

                }
            }

            let minvalue = Math.min.apply(null, combination.map(item => Math.abs(item.value)))
            result = combination.filter(item => Math.abs(item.value) == minvalue)
            result = result.map(item => {
                return { '单价': item.arr, "数量": item.arr1 }
            })
            return result
        }
        console.log(JSON.stringify(sum(arr, arr1), null, 2))
    </script>
</body>

</html>

数据前后对比


<!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>
        // 新数组
        let arr = [{
            weight: 1,
            name: 1,
            id: 1,
        }, {
            weight: 2,
            name: 2,
            id: 2,
        }, {
            weight: 3,
            name: 3,
            id: 3,
        }];
        // 旧数组
        let arr1 = [{
            weight: 1,
            name: 1,
            id: 1,
        }, {
            weight: 3,
            name: 2,
            id: 2,
        }];

        // 新旧数据对比
        let new_result = [],
            old_resuld = [];

        // 新数据变化
        arr.forEach((item, index) => {
            // 相对的数据,看其他值等否
            let ismodel = arr1.find((zitem, zindex) => {
                return zitem.id == item.id;
            });
            if (ismodel && ismodel.weight != item.weight) {
                new_result.push(item);
            }
            if (!ismodel) {
                new_result.push(item);
            }
            // 如果没有 则加入数据组
            // let ismodel1 = arr1.some((zitem, zindex) => {
            //     return zitem.id == item.id;
            // });

            // if (!ismodel1) {
            //     new_result.push(item);
            // }
        });

        // 旧数据变化
        arr1.forEach((item, index) => {
            // 旧数据是否有 有看其他是否相对
            let ismodel = arr.find((zitem, zindex) => {
                return zitem.id == item.id;
            });
            if (ismodel && ismodel.weight != item.weight) {
                old_resuld.push(item);
            }

            if (!ismodel) {
                old_resuld.push(item);
            }

            // 旧数据是否有 没有直接加入
            // let ismodel1 = arr.some((zitem, zindex) => {
            //     return zitem.id == item.id;
            // });

            // if (!ismodel1) {
            //     old_resuld.push(item);
            // }
        });

        console.log(new_result, old_resuld, '=======new_result')


        let data1 = [], data3 = [];
        new_result.forEach((item) => {
            data1.push({
                weight: item.weight,
                name: item.name,
                id: item.id,

            });
            let ismodel1 = old_resuld.some((zitem, zindex) => {
                return zitem.id == item.id;
            });

            if (!ismodel1) {
                data3.push({
                    weight: 0,
                    name: item.name,
                    id: item.id,
                });
            }
        });

        old_resuld.forEach((item) => {
            let ismodel1 = new_result.some((zitem, zindex) => {
                return zitem.id == item.id;
            });
            if (!ismodel1) {
                data1.push({
                    weight: 0,
                    name: item.name,
                    id: item.id,
                });
            }
            data3.push({
                weight: item.weight,
                name: item.name,
                id: item.id,
            });
        });

        // 排序内容
        let new_data3 = [];
        data1.forEach((item) => {
            let zitem = data3.find((zitem) => {
                return item.id == zitem.id;
            });
            new_data3.push(zitem);
        });



        console.log(data1, data3, new_data3, "===new_result123");



    </script>
</body>

</html>

按数字排序


<!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>
        // 数据排序
        let arr = [{
            name: 1,
            value: 1,
        }, {
            name: 2,
            value: 2,
        }, {
            name: 3,
            value: 3,
        }];

        let arr1 = [{
            name: 2,
            value: 2,
        }, {
            name: 1,
            value: 1,
        }, {
            name: 3,
            value: 3,
        }];

        // 方式一
        let new_arr1 = [];
        arr.forEach((item, index) => {
            let sitem = arr1.find((zitem, index) => {
                return item.value == zitem.value
            })
            new_arr1.push(sitem)
        })

        console.log(arr, arr1, new_arr1, '===new_arr')

        // 方式二
        let obj_arr1 = {}, new_arr12 = []
        arr1.forEach((item, index) => {
            obj_arr1[item.value] = item
        })

        arr.forEach((item) => {
            new_arr12.push(obj_arr1[item.value])
        })
        console.log(arr, arr1, new_arr12, '===new_arr')
    </script>
</body>

</html>

对象路径(树的遍历) a.数据扁平化 b.多层遍历寻找上一层


<!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>
      const arr = [
        {
          id: "1",
          title: "a",
          children: [
            {
              id: "33",
              title: "axx",
              children: [
                {
                  id: "121115",
                  title: "hh",
                  children: [{ id: "121111", title: "hh1" }],
                },
              ],
            },
            { id: "34", title: "xxddf" },
          ],
        },
        { id: "2", title: "bxx" },
        //  略...
      ];

      let result = [];

      function arrType(arr, key, trage) {
        return arr.find((item) => {
          if (item.constructor === Object) {
            if (item[key] == trage) {
              return item;
            }

            if (Array.isArray(item.children)) {
              console.log(
                arguments.callee(item.children, key, trage).title,
                "===arguments.callee(item.children,key, trage)"
              );
              if (
                result.indexOf(
                  arguments.callee(item.children, key, trage).title
                ) == -1
              ) {
                result.unshift(
                  arguments.callee(item.children, key, trage).title
                );
              }

              return arguments.callee(item.children, key, trage);
            }
          }
        });

        console.log(ss, "===");
      }

      let ma = arrType(arr, "id", 121111);
      result.unshift(ma.title);
      console.log(result, "====");
    </script>
  </body>
</html>

树算法


<!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>
      let arr = [
        {
          label: "一级 1",
          sortNum: "1",
          children: [
            {
              sortNum: "1.1",
              label: "二级 1-1",
              children: [
                {
                  sortNum: "1.1.1",
                  label: "三级 1-1-1",
                },
                {
                  sortNum: "1.1.2",
                  label: "三级 1-1-2",
                },
                {
                  sortNum: "1.1.3",
                  label: "三级 1-1-3",
                },
                {
                  sortNum: "1.1.4",
                  label: "三级 1-1-4",
                },
              ],
            },
            {
              sortNum: "1.2",
              label: "二级 2-1",
              children: [
                {
                  sortNum: "1.2.1",
                  label: "三级 1-2-1",
                },
                {
                  sortNum: "1.2.2",
                  label: "三级 1-2-2",
                },
                {
                  sortNum: "1.2.3",
                  label: "三级 1-2-3",
                },
                {
                  sortNum: "1.2.4",
                  label: "三级 1-2-4",
                },
              ],
            },
          ],
        },
        {
          label: "一级 2",
          sortNum: "2",
          children: [
            {
              sortNum: "2.1",
              label: "二级 2-1",
              children: [
                {
                  sortNum: "2.1.1",
                  label: "三级 2-1-1",
                },
                {
                  sortNum: "2.1.2",
                  label: "三级 2-1-2",
                },
                {
                  sortNum: "2.1.3",
                  label: "三级 2-1-3",
                },
                {
                  sortNum: "2.1.4",
                  label: "三级 2-1-4",
                },
              ],
            },
          ],
        },
      ];

      function removeindex(value) {
        let newarr = [],
          index = 0;
        let resolution = value.split(".");
        console.log(resolution, "==");
        if (resolution.length == 1) {
          // 第一层内容
          arr.forEach((item) => {
            index++;
            if (item.sortNum != value) {
              item.sortNum = String(index);
              newarr.push(item);
            }
          });
        } else if (resolution.length == 2) {
          console.log("value", value);
          // 第一层内容
          arr.forEach((item) => {
            index = 0;
            item.children = item.children.filter((zitem) => {
              index++;
              if (zitem.sortNum != value) {
                zitem.sortNum = item.sortNum + "." + index;
                return zitem;
              }
            });
            newarr.push(item);
          });
        } else if (resolution.length == 3) {
          arr.forEach((item) => {
            item.children.forEach((zitem) => {
              index = 0;
              zitem.children = zitem.children.filter((sitem) => {
                index++;
                if (sitem.sortNum != value) {
                  sitem.sortNum = zitem.sortNum + "." + index;
                  return sitem;
                }
              });
            });
            newarr.push(item);
          });
        }

        return newarr;
      }
      console.log(JSON.stringify(removeindex("1.1.1"),null,2));
    </script>
  </body>
</html>

算法精简


<!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>
    <input id="user" type="text" type="text" />
    <span style="display: none" id="usererror"
      ><b style="color: #f00">用户输入框不能为空</b></span
    >
    <br />
    <input id="psd" type="password" type="text" />
    <span style="display: none" id="psderror"
      ><b style="color: #f00">密码入框不能为空</b></span
    ><br />
    <button id="bnt">登录</button>
    <script>
      let user = document.getElementById("user");
      let psd = document.getElementById("psd");
      let usererror = document.getElementById("usererror");
      let psderror = document.getElementById("psderror");
      let bnt = document.getElementById("bnt");

      // 原始数据
      //   user.onblur = function () {
      //     console.log(this.value, "==this");
      //     if (this.value === "") {
      //       usererror.style.display = "inline-block";
      //     } else {
      //       usererror.style.display = "none";
      //     }
      //   };
      //   psd.onblur = function () {
      //     console.log(this.value, "==this");
      //     if (this.value === "") {
      //       psderror.style.display = "inline-block";
      //     } else {
      //       psderror.style.display = "none";
      //     }
      //   };
      // 改良版本
      let arr = [usererror, psderror];
      [user, psd].forEach((item, i) => {
        item.onblur = function () {
          if (this.value === "") {
            arr[i].style.display = "inline-block";
          } else {
            arr[i].style.display = "none";
          }
        };
      });

      // 原始数据
      //   bnt.onclick = function () {
      //     let uservalue = user.value;
      //     let psdvalue = psd.value;
      //     if (uservalue == "") {
      //       usererror.style.display = "inline-block";
      //     }
      //     if (psdvalue == "") {
      //       psderror.style.display = "inline-block";
      //     }
      //     if (psdvalue == "" || uservalue == "") {
      //       return;
      //     }
      //     if (uservalue == "admin" && psdvalue == "123") {
      //       alert("登录成功!");
      //     } else {
      //       alert("用户名或密码登录不正确!");
      //     }
      //   };
      // 改良版本
      bnt.onclick = function () {
        let liist = [user, psd];
        let index = 0;
        liist.forEach((item, i) => {
          if (item.value == "") {
            arr[i].style.display = "inline-block";
          } else if (
            (i == 0 && item.value == "admin") ||
            (i == 1 && item.value == "123")
          ) {
            index++;
          } else {
            index += 2;
          }
        });
        if (index === 2) {
          alert("登录成功!");
        } else if (index > 2) {
          alert("用户名或密码登录不正确!");
        }
      };
    </script>
  </body>
</html>

求某个数相近值


<!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>
        let arr = [9980, 998, 499, 198, 99, 50, 30, 20, 10];
        let arr1 = [1, 1, 5, 7, 13, 5, 15, 13, 11, 46];
        let result = [];
        let combination = []

        for (let i = 0; i < arr.length; i++) {
            for (let j = 0; j < arr1.length; j++) {
                combination.push({
                    arr: arr[i],
                    arr1: arr1[j],
                    value: arr[i] * arr1[j] - 9980
                })

            }
        }

        let minvalue = Math.min.apply(null, combination.map(item => Math.abs(item.value)))
        result = combination.filter(item => Math.abs(item.value) == minvalue)

        console.log(combination, result, '===')







    </script>
</body>

</html>

数组对象去重


<!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>
        const data = [
            {
                sgbh: "20200701003",
                qywz: "分离器1",
                ch: "1",
                cwmc: "T2l4雷四段",
            },
            {
                sgbh: "20200701003",
                qywz: "分离器1",
                ch: "1",
                cwmc: "T2l4雷三段",
            },
            {
                sgbh: "20200701003",
                qywz: "分离器3",
                ch: "2",
                cwmc: "T2l4雷四段",
            },
            {
                sgbh: "20200701003",
                qywz: "分离器3",
                ch: "2",
                cwmc: "T2l4雷四段",
            },
        ]

        // 第一步去重
        let new_Data = []
        data.forEach((item, index) => {
            if (new_Data.length > 0) {
                let islock = new_Data.some((zitem, zindex) => {
                    if (item instanceof Object) {
                        let lock = true;
                        for (let key in zitem) {
                            if (item[key] !== zitem[key]) {
                                lock = false;
                            }
                        }
                        if (lock) {
                            return lock
                        }

                    }

                })

                if (!islock) {
                    new_Data.push(item)
                }
            } else {
                new_Data.push(item)
            }
        })

        console.log(new_Data, '===new_Data')

        new_Data = data

        // 第二步 数据合并
        let new_result = [];
        new_Data.forEach((item, index) => {
            if (new_result.length > 0) {
                let new_index = new_result.findIndex((zitem, index) => {
                    return zitem.label === item.qywz
                })
                if (new_index == -1) {
                    new_result.push({
                        value: item.qywz,
                        label: item.qywz,
                        children: [
                            {
                                value: item.ch,
                                label: item.ch,
                                children: [
                                    {
                                        value: item.cwmc,
                                        label: item.cwmc
                                    }
                                ]
                            }
                        ]
                    })
                } else {
                    let new_children_index = new_result[new_index].children.findIndex((zitem, index) => {
                        return zitem.label === item.ch

                    })
                    if (new_children_index == -1) {
                        new_result[new_index].children.push({
                            value: item.ch,
                            label: item.ch,
                            children: [
                                {
                                    value: item.cwmc,
                                    label: item.cwmc
                                }
                            ]
                        })
                    } else {
                        let new_children_children_index = new_result[new_index].children[new_children_index].children.findIndex((zitem, index) => {
                            return zitem.label === item.cwmc

                        })
                        console.log(new_children_children_index, '====new_children_children_index')
                        if (new_children_children_index == -1) {
                            new_result[new_index].children[new_children_index].children.push({
                                value: item.cwmc,
                                label: item.cwmc
                            })
                        }

                    }
                }

            } else {
                new_result.push({
                    value: item.qywz,
                    label: item.qywz,
                    children: [
                        {
                            value: item.ch,
                            label: item.ch,
                            children: [
                                {
                                    value: item.cwmc,
                                    label: item.cwmc
                                }
                            ]
                        }
                    ]
                })
            }

        })


        console.log(new_result, '===new_result')




        let result = [
            {
                value: '分离器1',
                label: '分离器1',
                children: [
                    {
                        value: '1',
                        label: '1',
                        children: [
                            {
                                value: 'T2l4雷三段',
                                label: 'T2l4雷三段'
                            },
                            {
                                value: 'T2l4雷四段',
                                label: 'T2l4雷四段'
                            }
                        ]
                    }
                ]
            },
            {
                value: '分离器3',
                label: '分离器3',
                children: [
                    {
                        value: '2',
                        label: '2',
                        children: [
                            {
                                value: 'T2l4雷四段',
                                label: 'T2l4雷四段'
                            }
                        ]
                    }
                ]
            }
        ]
    </script>
</body>

</html>

数组中获取对应参数


<!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>
        var arr = [
            1, '医师', 2, '主任医师', 3, '药师', 4, '一级药师'];
        var narr = []

        let str = arr.join(',').split(',').forEach(((item, index, arr) => {
            if ((4 * index + 3) <= arr.length) {
                console.log(4 * index + 3, '===88', arr[(4 * index + 3)])
                narr.push(arr[(4 * index + 3)])

            }
        }))

        console.log(narr, '===narr')
    </script>
</body>

</html>

经典算法

冒泡排序算法

参考:https://www.runoob.com/w3cnote/bubble-sort.html

<!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>
         var arr = [1.3, 9, 7, 5]
         for (let i = 0; i < arr.length; i++) {
             for (let j = 0; j < arr.length - j-1; j++) {
                if (arr[j] > arr[j + 1]) {
                     var temp = arr[j + 1];
                     arr[j + 1] = arr[j];
                     arr[j] = temp;
                 }
             }
         }
         console.log(arr, '===')

        var arr = [1, 5, 3, 4]
        var index = 0;
        while (index < arr.length) {
            for (let i = 0; i < arr.length - index-1; i++) {
                if (arr[i] > arr[i + 1]) {
                    var temp = arr[i + 1];
                    arr[i + 1] = arr[i];
                    arr[i] = temp;
                }
            }
            index++
        }
        console.log(arr)
    </script>
</body>

</html>

插入排序算法

参考:https://www.runoob.com/w3cnote/insertion-sort.html


<!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>


        var arr = [1, 7, 5, 3];
        for (let i = 1; i < arr.length; i++) {
            for (let j = i; j > 0; j--) {
                if (arr[j - 1] > arr[j]) {
                    var tem = arr[j - 1];
                    arr[j - 1] = arr[j];
                    arr[j] = tem;
                }
            }
        }

        console.log(arr, '===arr')

        var arr1 = [1, 7, 5, 3];
        var index = 1;
        while (index < arr1.length) {
            for (let j = index; j > 0; j--) {
                if (arr1[j - 1] > arr1[j]) {
                    var temp = arr1[j - 1];
                    arr1[j - 1] = arr1[j]
                    arr1[j] = temp;

                }
            }
            index++
        }
        console.log(arr1, '===arr1');

    </script>
</body>

</html>

选择排序

参考:https://www.runoob.com/w3cnote/selection-sort.html


<!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>
        var arr = [5, 3, 2, 7];

        for (let i = 0; i < arr.length; i++) {
            var curent = i;  // 最小索引
            for (let j = i + 1; j < arr.length - i; j++) {
                if (arr[curent] > arr[j]) {
                    curent = j
                }
            }
            var temp = arr[i];
            arr[i] = arr[curent];
            arr[curent] = temp;
        }

        console.log(arr, '===')
    </script>
</body>

</html>

其他算法-------------------------------

数组去重


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const curData = [
            { userName: '123' },
            { userName: '111' },
            { userName: '334' },
            { userName: '222' },
            { userName: '123' },
            { userName: '111' },
            { userName: '123' }
        ];

        let dataDeal = (data) => {
            let listArr = [];
            data.forEach(function (value, index) {
                let obj = [];
                for (let i = 0; i < listArr.length; i++) {
                    // 对比相同的字段key,相同放入对应的数组
                    if (listArr[i][0].userName == value.userName) {
                        listArr[i].push(value);
                        return;
                    }
                }
                // 第一次对比没有参照,放入参照
                obj.push(value);
                listArr.push(obj);

            });
            return listArr;
        };

        let resultDataDeal = dataDeal(curData);
        console.log('resultDataDeal===' + JSON.stringify(resultDataDeal));
    </script>
</body>

</html>

合并数组 对象同类

res.respBody.list=[
{
createTime: "2021/07/27"
createUserId: "383027193946587136"
id: "60ff78cb97749e47bf86fc89"
imageUrl: "https://ysch-user.oss-cn-shenzhen.aliyuncs.com/383027193946587136/app/avatar/383027193946587136/c147e55b44395fc51a7195d4ceaa4dee.png"
status: 1
userId: "383027193946587136"
},
{
createTime: "2021/07/27"
createUserId: "383027193946587136"
id: "60ff78cb97749e47bf86fc89"
imageUrl: "https://ysch-user.oss-cn-shenzhen.aliyuncs.com/383027193946587136/app/avatar/383027193946587136/c147e55b44395fc51a7195d4ceaa4dee.png"
status: 1
userId: "383027193946587136"
},
{
createTime: "2021/07/27"
createUserId: "383027193946587136"
id: "60ff78cb97749e47bf86fc89"
imageUrl: "https://ysch-user.oss-cn-shenzhen.aliyuncs.com/383027193946587136/app/avatar/383027193946587136/c147e55b44395fc51a7195d4ceaa4dee.png"
status: 1
userId: "383027193946587136"
},
{
createTime: "2021/07/28"
createUserId: "383027193946587136"
id: "60ff78cb97749e47bf86fc89"
imageUrl: "https://ysch-user.oss-cn-shenzhen.aliyuncs.com/383027193946587136/app/avatar/383027193946587136/c147e55b44395fc51a7195d4ceaa4dee.png"
status: 1
userId: "383027193946587136"
},
{
createTime: "2021/07/28"
createUserId: "383027193946587136"
id: "60ff78cb97749e47bf86fc89"
imageUrl: "https://ysch-user.oss-cn-shenzhen.aliyuncs.com/383027193946587136/app/avatar/383027193946587136/c147e55b44395fc51a7195d4ceaa4dee.png"
status: 1
userId: "383027193946587136"
}
]



  let figureList = []
        res.respBody.list.forEach(item => {
          if (
            figureList.length > 0 &&
            figureList.some((zitem) => zitem.createTime == item.createTime)
          ) {
            let index = figureList.findIndex(
              (sitem) => sitem.createTime == item.createTime
            );
            figureList[index].imageslist.push(item.imageUrl)
          } else {
            figureList.push({
              createTime: item.createTime,
              imageslist: [item.imageUrl]
            });
          }
        });

两数据合并 同类 并去重


<!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>
        var arr = [{
            name: 'zs',
            id: 1
        }, {
            name: 'lis',
            id: 2
        }, {
            name: 'wu',
            id: 3
        }]
        var arr1 = [{
            name: 'zs',
            id: 1
        }, {
            name: 'lis',
            id: 2
        }, {
            name: 'wu',
            id: 3
        }, {
            name: 'zl',
            id: 4
        }]
        let arr2 = []
        arr1.forEach((item) => {
            if (!arr.some((oitem) => oitem.id == item.id)) {
                arr2.push(item)
            }
        })

        console.log(arr2, '====')
    </script>
</body>

</html>

数组自定分组(固定个数 分数组)

<!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>
        var arr = [1, 2, 3, 4, 5, 6, 7], index = 4;

        let arr1 = [];
        function arrinit() {
            for (let i = 0; i < index; i++) {
                if ((i + 1) != index) {
                    arr1.push(arr.slice(Math.floor(arr.length / index) * i, Math.floor(arr.length / index) * (i + 1)))
                } else {
                    arr1.push(arr.slice(Math.floor(arr.length / index) * (i)))
                }

            }

        }
        arrinit()
        console.log(arr1)


    </script>
</body>

</html>

固定长度 分数组


<!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>
      let list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      let length = list.length;
      let length1 = parseInt(length / 3);
      let arr = [];

      let oi = 0;

      for (let i = 0; i < length1; i++) {
        if (i == length1 - 1) {
          arr.push(list.slice(i * 3, (i + 1) * 3));
          arr.push(list.slice((i + 1) * 3));
        } else {
          arr.push(list.slice(i * 3, (i + 1) * 3));
        }
      }
      console.log(arr, "===arr");

      for (let i = 0; i < length1; i++) {
        console.log(list.splice(0, 3), "===");
      }

   
    </script>
  </body>
</html>

数组的索引内容

<!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>
        var arr = [1, 2, 3, 4, 5, 6, 7], index = 4;


        function arrinit(arr, index) {
            let arr1 = [];
            for (let i = 0; i < index; i++) {
                if ((i + 1) != index) {
                    arr1.push([Math.floor(arr.length / index) * i, Math.floor(arr.length / index) * (i + 1)])
                } else {
                    arr1.push([Math.floor(arr.length / index) * (i), arr.length - 1])
                }

            }
            return arr1

        }

        console.log(arrinit(arr, index))



    </script>
</body>

</html>

字符串转换


<!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>
        function issfate(s) {
            if (typeof s == 'string' && 1 <= s.length && s.length <= 15) {
                var arr = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
                for (let i = 0; i < s.length; i++) {
                    if (!arr.includes(s[i])) {
                        return true
                    }
                }
                return false
            } else {
                return true
            }
        }
        var romanToInt = function (s) {
            if (!issfate(s)) {
                var arr = { I: ['V', 'X'], X: ['L', 'C'], C: ['D', 'M'] };
                var obj = {
                    I: 1,
                    V: 5,
                    X: 10,
                    L: 50,
                    C: 100,
                    D: 500,
                    M: 1000,
                    IV: 4,
                    IX: 9,
                    XL: 40,
                    XC: 90,
                    CD: 400,
                    CM: 900
                }
                var k = 0, isbool = false;


                for (var j = 0; j < s.length; j++) {
                    if (isbool) {
                        isbool = false
                        continue
                    }
                    if (s[j] in arr && arr[s[j]].includes(s[j + 1])) {
                        k += obj[s.slice(j, j + 2)]

                        isbool = true
                    } else {
                        k += obj[s.slice(j, j + 1)]
                        isbool = false
                    }
                }
                console.log(k, '===')

            }

        };
        var ss = "III"
        romanToInt(ss)
           // 解体思路 按部就班 先判断是不是特殊字段 不是进一位 是特殊字段进行判断
    </script>
</body>

</html>

字符串转换II


<!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>

        var romanToInt = function (s) {

            var obj = {
                I: 1,
                V: 5,
                X: 10,
                L: 50,
                C: 100,
                D: 500,
                M: 1000,
                IV: 4,
                IX: 9,
                XL: 40,
                XC: 90,
                CD: 400,
                CM: 900
            }
            var isbool = false, k = 0;
            for (var j = 0; j < s.length; j++) {
                if (isbool) {
                    isbool = false
                    continue
                }
                if (obj[s.slice(j, j + 2)]) {
                    k += obj[s.slice(j, j + 2)]
                    isbool = true
                } else {
                    k += obj[s.slice(j, j + 1)]
                    isbool = false
                }
            }
            console.log(k, '===')

        };
        var ss = "III"
        romanToInt(ss)
       // 解体思路 先取特殊的两位 进行比较 如果可以进行下去 不可以返回比较一位
    </script>
</body>

</html>

数组组合的最大面积


<!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>
        var maxArea = function (height) {
            let max = 0, water = 0, len = height.length;
            for (let i = 0; i < len - 1; i++) {
                if (height[i] > (max / len - 1 - i)) {  // 判断 数值比最大的是否都大 后进行处理
                    for (let j = 1; j < len - i; j++) {
                        water = Math.min(height[i], height[i + j]) * j
                        if (max < water) {
                            max = water
                        }
                    }
                }

            }
            return max
        };
        var n = [1, 8, 6, 2, 5, 4, 8, 3, 7];
        console.log(maxArea(n));

        var maxArea = function (height) {
            let len = height.length;
            let max = 0, water = 0;
            for (let i = 0; i < len - 1; i++) {
                if (height[i] > max / (len - i - 1)) {
                    for (let j = i + 1; j < len; j++) {
                        water = (j - i) * Math.min(height[i], height[j]);
                        if (max < water)
                            max = water;
                    }
                }
            }
            return max;

        };

          var maxArea = function (height) {
            // debugger
            let start = 0, end = height.length - 1, max = 0, water = 0;
            while (start < end) {
                if (height[start] > height[end]) {
                    water = height[end] * (end - start)
                    end--
                } else {
                    water = height[start] * (end - start)
                    start++

                }

                if (max < water) {
                    max = water
                }

            }
            return max;

        };
       // 双指针 解法
    </script>
</body>

</html>

数组最长相同字符串


<!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>
        var longestCommonPrefix = function (strs) {
            let com = strs[0], max = "", isbool = true;

            for (let i = 0; i < strs.length; i++) {
                if (com.length > strs[i].length) {
                    com = strs[i]
                }
            }

            console.log(com, '===com')

            for (let j = 0; j < com.length; j++) {
                for (let i = 0; i < strs.length; i++) {
                    if (strs[i][j] !== com[j]) {
                        isbool = false
                    }
                }
                if (isbool) {
                    max += com[j]
                }

            }
            return max
        };
        var n = ["dog", "racecar", "car"]
        console.log(longestCommonPrefix(n))
        //  最短字符串的最长 字符 
           function sicom(str1, str2) {
            var index = 0
            var length = Math.min(str1.length, str2.length)
            while (index < length && str1.charAt(index) == str2.charAt(index)) {
                index++
            }
            return str1.substring(0, index);
        };

        var longestCommonPrefix = function (strs) {
            let start = strs[0];
            for (let i = 0; i < strs.length; i++) {
                start = sicom(start, strs[i])
                if (start.length == 0) {
                    break;
                }
            }

            return start

        };
       // 横向扫描法
    </script>
</body>

</html>

获取对象中的某个最大值 最小值



<!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>
        let obj = {
            age: 1,
            height: 172,
            wline: 64,
        }
        let obj2 = {
            age: 2,
            height: 173,
            wline: 65,
        }
        let obj3 = {
            age: 3,
            height: 174,
            wline: 66,
        }

        let obj4 = {
            age: 4,
            height: 175,
            wline: 67,
        }

        let obj5 = {
            age: '年龄',
            height: '身高'
        }

        let arr = []
        for (let key in obj) {
            if (key in obj5) {
                arr.push({
                    name: obj5[key],
                    max: [obj2, obj3, obj4].sort((a, b) => {
                        return a[key] - b[key]
                    })[2],
                    min: [obj2, obj3, obj4].sort((a, b) => {
                        return a[key] - b[key]
                    })[0]
                })
            }
        }

        console.log(arr, '===arr')

        // let arr = [obj, obj3, obj2]
        // let arr1 = arr.sort((a, b) => {
        //     return a.age - b.age
        // })
        // console.log(arr, arr1, '===')

    </script>
</body>

</html>

感悟: 对于数据的最大 最小 可以转化成数组处理(排序问题) Math.max() 函数 分析问题 ->解决思路->实现算法

数组最大值


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
    /* 控制另外一个元素改变, 这样写无效 , 用~ 也无效 */
    .phone-nav:hover+.account-nav {
        color: red
    }
</style>

<body>
    <div class="login_nav">
        <span class="phone-nav">2222qqqqqqqqqqq</span>
        <span class="account-nav">1111qqqqqqqqqqqqq1</span>
    </div>
</body>
<script>

    const list = [
        {
            name: "张三",
            id: 1,
            amount: 1,
            balance: 1,
            date: "2022-01-02",
        },
        {
            name: "张三",
            id: 2,
            amount: 1,
            balance: 1,
            date: "2022-01-04",
        },
        {
            name: "张三",
            id: 3,
            amount: 15,
            balance: 15,
            date: "2022-01-05",
        },
        {
            name: '张三',
            id: 33,
            amount: 33,
            balance: 33,
            date: '2022-01-05'
        },
        {
            name: "张三",
            id: 4,
            amount: 1,
            balance: 1,
            date: "2022-02-01",
        },
        {
            name: "张三",
            id: 5,
            amount: 1,
            balance: 1,
            date: "2022-02-02",
        },
        {
            name: "张三",
            id: 6,
            amount: 26,
            balance: 26,
            date: "2022-02-06",
        },
        {
            name: '张三',
            id: 66,
            amount: 66,
            balance: 66,
            date: '2022-02-06'
        },
        {
            name: "李四",
            id: 7,
            amount: 1,
            balance: 1,
            date: "2022-01-02",
        },
        {
            name: "李四",
            id: 8,
            amount: 1,
            balance: 1,
            date: "2022-01-03",
        },
        {
            name: "李四",
            id: 9,
            amount: 215,
            balance: 215,
            date: "2022-01-05",
        },
        {
            name: "李四",
            id: 10,
            amount: 1,
            balance: 1,
            date: "2022-02-01",
        },
        {
            name: "李四",
            id: 11,
            amount: 1,
            balance: 1,
            date: "2022-02-03",
        },
        {
            name: "李四",
            id: 12,
            amount: 225,
            balance: 225,
            date: "2022-02-05",
        },
        {
            name: "李四",
            id: 13,
            amount: 1,
            balance: 1,
            date: "2022-03-01",
        },
        {
            name: "李四",
            id: 14,
            amount: 1,
            balance: 1,
            date: "2022-03-05",
        },
        {
            name: "李四",
            id: 15,
            amount: 236,
            balance: 236,
            date: "2022-03-06",
        },
        {
            name: "李四",
            id: 16,
            amount: 212,
            balance: 212,
            date: "2022-03-06",
        },
        {
            name: "李四",
            id: 17,
            amount: 234,
            balance: 234,
            date: "2022-03-06",
        }
    ];

    // 获取数组对象中,不同id,相同日期和名称中最大的一天

    function max({ different = [], TheSame = [], arr = [], target = "", type = 'all' }) {
        // console.log(TheSame, different, '===')
        let total = [];
        arr.forEach((item, index) => {
            let i = total.findIndex((sitem, sindex) => {
                if (sitem) {
                    // console.log(sitem, '==sitem')
                    return sitem.some((kitem) => {
                        return TheSame.every(hitem => {
                            return kitem[hitem] == item[hitem]
                        })

                    })
                }

            })
            if (i != -1) {
                total[i].push(item)
            } else {
                total.push([item])
            }

        })

        let List = total.map((item) => {
            return Math.max.apply(null, item.map((item => {
                if (typeof item[target] == 'string' && item[target].indexOf('-')) {
                    return item[target].replace(/-/g, '') * 1
                } else if (typeof item[target] == 'number') {
                    return item[target]
                } else {
                    return 0
                }

            })));
        })

        if (type == 'all') {
            let maxList = total.map((item, index) => {
                return item.find(zitem => {
                    if (typeof zitem[target] == 'string' && zitem[target].indexOf('-')) {
                        return zitem[target].replace(/-/g, '') == List[index]
                    } else if (typeof zitem[target] == 'number') {
                        return zitem[target] == List[index]
                    } else {
                        return 0
                    }
                })
            })

            return maxList
        } else if (type == 'every') {
            let max = Math.max(...List)

            let maxList = arr.find((item, index) => {
                return item[target] == max
            })

            return maxList
        }



    }
    // console.log(list.length, '===')

    console.log(max({ different: ['id'], TheSame: ['date', 'name'], arr: list, target: 'id', type: 'every' }))

</script>

</html>

算法链接

添加链接描述 132
对于联动 相关联的需求

  1. 分布处理 考虑每一种情况 列举出每一种 情况 性能开销小 不好维护
  2. 枚举 每一种情况 统一调用 复杂度最小 性能开销会大些 比较好维护
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web修理工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值