繁体   English   中英

javascript:重复时拆分多维数组

[英]javascript: split multidimension array upon duplicates

我一直坚持根据成对和重复将数组分成多个部分。

我有这个数组:

var array = [[24, 17],[45, 17],[17, 24],[38, 31],[31, 38],[17, 45]];

我需要将其拆分以获取此内容:

var array = [[24,17,45],[38,31]];

有人对正确的方法有任何想法吗? 任何帮助将不胜感激 !

您可以使用Set的功能,并检查值之一是否已在一组中。 如果不是,请使用新集创建新结果集。

 var array = [[24, 17], [45, 17], [17, 24], [38, 31], [31, 38], [17, 45]], result = array .reduce((r, a) => { var s = r.find(s => a.some(Set.prototype.has, s)); if (s) { a.forEach(v => s.add(v)); } else { r.push(new Set(a)); } return r; }, []) .map(s => Array.from(s)); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以通过展开Array.concat()来展平数组,然后缩小数组。 使用帮助器Set ,当检测到重复项时添加一个新的子数组。 然后,过滤掉空数组:

 const array = [[24, 17],[45, 17],[17, 24],[38, 31],[31, 38],[17, 45]]; const helperSet = new Set(); const result = [].concat(...array) .reduce((r, n) => { !r[r.length - 1] && r.push([]); if(!helperSet.has(n)) { r[r.length - 1].push(n) helperSet.add(n); } else { r.push([]); }; return r; }, []) .filter(({ length }) => length); console.log(result); 

您可以使用将特定网格映射到碰撞的哈希表,因此可以轻松地将它们分组:

 const array = [[24, 17],[45, 17],[17, 24],[38, 31],[31, 38],[17, 45]]; const result = [], hash = {}; for(const [a, b] of array) { let group = hash[a] || hash[b] || (arr => (result.push(arr), hash[a] = hash[b] = arr))([]); if(!group.includes(a)) group.push(a); if(!group.includes(b)) group.push(b); } console.log(result); 

暂无
暂无

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

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