乐趣区

分享两个偶尔能用的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]
退出移动版