[英]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);
這可以通過兩步過程完成:
Set
刪除任何重復的元素.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.