代码之家  ›  专栏  ›  技术社区  ›  user3142695

从嵌套数组中删除多个元素

  •  0
  • user3142695  · 技术社区  · 4 年前

    假设有这样一个嵌套数组:

    [
        [ 'one', 'third ],
        [ 'one', 'second', 'fourth' ],
        [ 'one', 'third' ],
    ]
    

    因此,结果应该是:

    [
        [ 'one', 'third ],
        [ 'second', 'fourth' ],
        [],
    ]
    

    我会迭代每个数组和每个元素,但这只会从下一个数组中删除一个元素(如果循环在最后一个数组中,则缺少最后一个数组或错误),而且感觉非常粗糙。。。

    for (let i = 0; i < array.length; i++) {
        const element = array[i];
        for (let j = 0; j < element.length; j++) {
            const string = element[j];
            const index = array[i + 1].indexOf(string)
            if (index !== -1) {
                array[i + 1].splice(index, 1)
            }
        }
    }
    
    3 回复  |  直到 4 年前
        1
  •  2
  •   Nina Scholz    4 年前

    你可以休息一下 Set 并使用查找筛选值,如果未看到,则添加值。

    const
        values = new Set,
        data = [['one', 'third'], ['one', 'second', 'fourth'], ['one', 'third']],
        result = data.map(a => a.filter(v => !values.has(v) && values.add(v)));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
        2
  •  0
  •   Ro Milton    4 年前

    它也可以使用不可变的编程 reduce() flat()

    const data = [[ 'one', 'third' ], [ 'one', 'second', 'fourth' ],[ 'one', 'third' ]];
    const result = data.reduce((acc, val) => [
         ...acc,
         val.filter(item => !acc.flat().includes(item))
    ], []);
    
    console.log(result);
        3
  •  0
  •   Carsten Massmann    4 年前

    .forEach() 还有一份杂烩 u 要跟踪已遇到的数组元素,请执行以下操作:

    const arr=[
    [ 'one', 'third' ],
    [ 'one', 'second', 'fourth' ],
    [ 'one', 'third' ],
    ];
    
    const res=[], u={};
    arr.forEach(r=>{
      res.push([]);
      r.forEach((c,i)=>{
       u[c] || (u[c]=res[res.length-1].push(c))
    })});
    
    console.log(res);