美文网首页
数组常用方法

数组常用方法

作者: 饥人谷_刘康 | 来源:发表于2020-01-10 16:20 被阅读0次

    1.去除数组中的无效/无用值

    const compact = arr => arr.filter(Boolean);
    
    compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 
    // [ 1, 2, 3, 'a', 's', 34 ]
    

    2.检测数值出现次数

    const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
    countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
    

    3.递归扁平化deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

    (5) [1, 2, 3, 4, 5]数组(降维)

    const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
    deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
    
    

    4.指定深度扁平化数组

    const flatten = (arr, depth = 1) =>
      arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
    
    flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
    flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
    
    

    5.两数组的交集

    const intersection = (a, b) => {
      const s = new Set(b);
      return a.filter(x => s.has(x));
    };
    
    intersection([1, 2, 3], [4, 3, 2]); // [2, 3]
    
    

    6.根据parent_id生成树结构

    const nest = (items, id = null, link = 'parent_id') =>
      items
        .filter(item => item[link] === id)
        .map(item => ({ ...item, children: nest(items, item.id) }));
    
    

    用法

    const comments = [
      { id: 1, parent_id: null },
      { id: 2, parent_id: 1 },
      { id: 3, parent_id: 1 },
      { id: 4, parent_id: 2 },
      { id: 5, parent_id: 4 }
    ];
    const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]
    
    image.png

    相关文章

      网友评论

          本文标题:数组常用方法

          本文链接:https://www.haomeiwen.com/subject/evipactx.html