简体   繁体   English

Javascript 合并 arrays 具有相同的值

[英]Javascript merge arrays with same values

I want to merge arrays which includes same values to one array with javascript.我想将包含相同值的 arrays 与 javascript 合并到一个数组中。

Example: Input array:示例:输入数组:

neighbours = [
 [0, 1],
 [1, 0, 2],
 [2, 1],
 [3, 4, 5],
 [4, 3, 6],
 [5, 3, 6],
 [6, 4, 5]
];

Output array: Output 阵列:

pairs = [
 [0, 1, 2],
 [3, 4, 5, 6]
]

Is there a simple way to do this in javascript?在 javascript 中是否有一种简单的方法可以做到这一点?

Here is a bruteforce solution.这是一个蛮力解决方案。 hope its the one which you are looking for.希望它是您正在寻找的那个。

var neighbors = [
     [0, 1],
     [1, 0, 2],
     [2, 1],
     [3, 4, 5],
     [4, 3, 6],
     [5, 3, 6],
     [6, 4, 5]
];
var pairs=[];

pairs.push(neighbors[0]); 
var idx=0;
for(var i=1;i<neighbors.length;i++){
    var cur=neighbors [i];
var prev=neighbors [i-1];
var found=false;
for(var j=0;j<prev.length;j++){
    for(var k=0;k<cur.length;k++){
        if(prev[j]==cur[k]){
            found=true;
            if(!pairs[idx]) pairs[idx]=[];
            pairs[idx].push(cur);
            break;
        }
    }
    if(found) break;
    }
    if(!found) idx++;
}

for(var j=0;j<pairs.length;j++){
    pairs[j]=[...new Set(pairs[j].flat(Infinity))].sort((a,b)=>(a-b));

}
console.log(pairs);

let me know if you need explanation of it.如果您需要解释,请告诉我。

Using object keys as set values try to repeatedly merge the sets into each other.使用 object 键作为设置值会尝试将这些集合重复合并到彼此中。

 const neighbours = [ [0, 1], [1, 0, 2], [2, 1], [3, 4, 5], [4, 3, 6], [5, 3, 6], [6, 4, 5] ]; const neighbourSets = neighbours.map( list => list.reduce((a,v)=>(a[v]=undefined,a),{}) ); let pairs = []; let next = neighbourSets.shift(); while(next) { const neighbourCount = Object.keys(next).length; for(const [index, pairCandidate] of Object.entries(pairs) ) { const merged = Object.assign({}, next, pairCandidate); // Check if there is overlap. if(Object.keys(merged).length < neighbourCount+Object.keys(pairCandidate).length) { delete pairs[index]; next = merged; } } pairs.push(next); next = neighbourSets.shift(); } pairs = pairs.filter(v=>v).map( o=>Object.keys(o).map(v=>Number(v)).sort() ); console.log(pairs);

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

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