js如何把拥有相同项的数组合并?

前端打更人
  • 7

例如:
arr1 = [["26","27"],["28","27"],["22","21"]]
输出结果为[["26","27","28"],["22","21"]]
arr2 = [["26","27","28"],["26","27","28","29"],["22","21"]]
输出结果为[["26","27","28","29"],["22","21"]]

该如何实现呢? 求教!

回复
阅读 2.9k
7 个回答
普拉斯强
  • 2.6k
✓ 已被采纳
function trans(arr) {
  return arr.reduce((list, subList) => {
    const set = list.find(set => {
      return subList.some(num => set.has(num))
    })
    if(set) {
      subList.forEach(set.add.bind(set))
    } else {
      list.push(new Set(subList))
    }
    return list;
  }, [])
  .map(set => {
    return [...set]
  })
}

console.log(trans([["26","27","28"],["26","27","28","29"]]))
console.log(trans([["26","27"],["28","27"],["22","21"]]))
落叶
  • 329

let arr1= [["26","27","28"],["26","27","28","29"]]
Array.from(new Set(arr1.flat()))

无心
  • 4
新手上路,请多包涵
 const arr2 = [["26","27","28"],["26","27","28","29"]];
 [...new Set( arr2.flat(Infinity))]
function merge(data, res=[]) {
            return data.reduce((pre, cur) => {
                let isIntsct = (pre.length + cur.length) === [...new Set([...pre, ...cur])].length;
                !isIntsct ? res.push([...new Set([...pre, ...cur])]) : res.push(cur)
                return res;
            })
        }

暴力法

function check(arr1, arr2) {
    return arr1.some(a1 => arr2.some(a2 => a1 === a2))
}
function merge(arr) {
    const result = []
    for (const a of arr) {
        let merged = false;
        for (const r of result) {
            if (check([...r], a)) {
                a.forEach(item => r.add(item))
                merged = true
            }
        }
        if (!merged) {
            result.push(new Set(a))
        }
        merged = false
    }
    return result.map(s => [...s])
}

这个问题其实是目标不明确,因为是二维数组,再转换到二维数组,但现在例子的规则并不完整,或者适当
比如输入:

arr2 = [["24","25"],["26","27","28"],['25',"26","27","28","29"],["22","21"]]

的输出该是什么?

输出可能1 = [["24","25","29"],["26","27","28"],["22","21"]]
输出可能2 = [["24","25","26","27","28","29"],["22","21"]]
...

一般对于类似的处理是把二级数组转换到一维数组,并去重

for (let i = 1; len = arr.length; i++) {
    const current = arr[i];
    
    for (let j = 0; j < i; j++) {
        const prev = arr[j];
        const newArr = [...new Set(prev.concat(current))];
        
        if (newArr.length !== prev.length + current.length) {
            arr[j] = newArr;
            arr.splice(i, 1);
            i--;
            break;
        }
    }
}
宣传栏