簡體   English   中英

從多個數組中查找唯一值跳過空數組

[英]Finding unique values from multiple arrays skipping empty arrays

注意:不是重復的問題..在這里我需要跳過空數組。

假設我有幾個數組,例如:

var a = [1, 2, 3, 4],
b = [2, 4],
c = [],
d = [4];

使用以下功能,我可以獲得所需的結果: [4]

 var a = [1, 2, 3, 4], b = [2, 4], c = [], d = [4]; var res = [a, b, c, d].reduce((previous, current) => !previous.length || previous.filter((x) => !current.length || current.includes(x)), ); console.log(res)

我包括!current.length || 以上繞過空數組c 但是,如果集合中的第一個數組即a為空,則這不起作用。 結果將是[]

過濾一下就好了使代碼更具可讀性

 var a = [1, 2, 3, 4], b = [2, 4], c = [], d = [4]; var res = [c, b, a, d].filter(arr => arr.length).reduce((previous, current) => previous.filter((x) => current.includes(x)), ); console.log(res)

此代碼將按您的預期工作(vanilla JS,支持舊瀏覽器):

 var a = [1, 2, 3, 4], b = [2, 4], c = [], d = [4]; var res = [a, b, c, d].reduce(function(acc, arr) { // ignore empty array if(arr.length == 0) return acc; // assign first non-empty array to accumudation if(acc.length == 0) return arr; // otherwise, accumudation will be insection of current accomudation and current array return acc.filter(function(n) { return arr.indexOf(n) !== -1; }); }, []); console.log(res)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM