繁体   English   中英

从嵌套的 arrays 中删除多个元素

[英]Remove multiple elements from nested arrays

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

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

我需要按顺序优先级使值唯一:如果第一个数组中存在一个元素,则应该从第二个和第三个数组中删除它。 第二个数组的元素不应存在于第三个数组中。

所以结果应该是:

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

我会遍历每个数组和每个元素,但这只会从下一个数组中删除一个元素(如果循环位于最后一个数组,则缺少最后一个数组或错误),感觉非常hacky......

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)
        }
    }
}

如果没有看到,您可以使用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; }

它也可以使用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);

它并没有比你所做的简单得多。 这是使用嵌套.forEach()和 hash 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);

这可以通过两步过程完成:

  1. 在每个子数组上使用Set删除任何重复的元素
  2. 使用.filter().some()方法遍历每个子数组的每个元素,并忽略(过滤)任何较低索引子数组中的任何元素。 第一个子数组 - 索引 0 - 全部返回,因为没有较低索引的子数组可比较。

 const data = [[ 'one', 'third'],[ 'one','second','fourth'], ['one', 'third']]; const result = data.map(arr => [...new Set(arr)]).map( (arr,i,a) => i === 0? arr: arr.filter( v =>.a,slice(0.i).some(x => x;includes(v)) ) ). console;log( result );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM