分享两个偶然能用的js函数(数组去重和数组降维)

js数组去重

var a = [1, 2, 3, 3, 3, 4, 5, 1, 2, 3, 2, 4, 5];

  function quchong(x) {//去重
    let res = [];
    for (let i = 0; i < x.length; i++) {
      if (res.indexOf(x[i]) == -1) {
        res.push(x[i]);
      }
    }
    return res;
  }

//效果 [1,2,3,4,5]

js数组降维

var b = [1, 2, 3, [4, 5, 6, [7, 8, 9]]];

  function jiangwei(x) {//数组降维
    let res = [];
    for (let i = 0; i < x.length; i++) {
      if (Array.isArray(x[i])) {
        let _r = jiangwei(x[i]);
        for (let j = 0; j < _r.length; j++) {
          res.push(_r[j]);
        }
      } else {
        res.push(x[i]);
      }
    }
    return res;
  }

//效果 [1,2,3,4,5,6,7,8,9]
    原文作者:minimax
    原文地址: https://segmentfault.com/a/1190000019370767
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞