zoukankan      html  css  js  c++  java
  • JavaScript数组扁平化、数组去重常见方法

    数组扁平化

    1.使用arr.flat()

    const arr = [1,[2,[3,[4,5]]], 6]
    const res = arr.flat(Infinity)
    

    2.使用正则

    const arr = [1,[2,[3,[4,5]]], 6]
    const res = JSON.stringify(arr).split(',').map(n=>Number.parseInt(n))
    

    3.正则版本2

    const arr = [1,[2,[3,[4,5]]], 6]
    const res = JSON.parse('[' + JSON.stringify(arr).replace(/[|]/g, '') + ']')
    

    数组去重

    1.使用Set

    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = Array.from(new Set(arr))
    

    2.使用indexOf

    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = []
    for(let i=0; i< arr.length; i++){
      if(res.indexOf(arr[i]) === -1) res.push(arr[i])
    }
    

    2.使用includes

    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = []
    for(let i=0; i< arr.length; i++){
      if(!res.includes(arr[i])) res.push(arr[i])
    }
    

    3.使用filter

    const arr = const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = arr.filter((item, index)=> arr.indexOf(item)===index)
    

  • 相关阅读:
    二维图像的DCT变换
    Shell脚本加密--shc/gzexe
    vim python插件--vim python mode
    移动端图片裁剪解决方案
    移动端压缩并ajax上传图片解决方案
    html5拖拽实现
    html5的触摸事件
    js循环添加事件的问题
    h5上传图片
    thinkphp加载第三方类库
  • 原文地址:https://www.cnblogs.com/pangqianjin/p/14871376.html
Copyright © 2011-2022 走看看