在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 數(shù)組雙重遍歷

數(shù)組雙重遍歷

var arr1 = [{
        id: 1,
        name: 'a'
    }, {
        id: 2,
        name: 'b'
    }, {
        id: 3,
        name: 'c'
    }, {
        id: 4,
        name: 'd'
    }, {
        id: 5,
        name: 'e'
    }, {
        id: 6,
        name: 'f'
    }];
        
    var arr2 = [{
        id: 1,
        name: 'a'
    }, {
        id: 4,
        name: 'd'
    }, {
        id: 7,
        name: 'g'
    }];

兩個(gè)數(shù)組 arr1arr2 求他們中 id 相同的項(xiàng)。有什么最優(yōu)的方案嗎?

回答
編輯回答
悶騷型

loadash intersection :

_.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }]

參考,內(nèi)部代碼應(yīng)該也是雙重便利。 https://lodash.com/docs/4.17.4

2018年1月5日 20:55
編輯回答
念初

兩個(gè)數(shù)組里面的項(xiàng)的id是遞增的嗎?

2018年4月19日 00:34
編輯回答
使勁操

提供一個(gè)用 Set 求交集的方法:

arr1 = new Set(arr1.map(i => i.id));
arr2 = new Set(arr2.map(i => i.id));
let intersectionSet = new Set([...arr1].filter(x => arr2.has(x)));
console.log(intersectionSet);
2017年3月1日 17:00
編輯回答
青裙

這個(gè)完全不需要數(shù)組雙重遍歷,一次遍歷就夠了。復(fù)雜度完全可以做到:

O = arr1.length + arr2.length + min(arr.length, arr2.length);

我的方案如下:

const [minArr, maxArr] = arr1.length > arr2.length ? [arr2, arr1] : [arr1, arr2];
const tempMaxArrObj = {};
maxArr.map(item => tempMaxArrObj[item.id] = item);  // m 的復(fù)雜度
minArrIdArr = minArr.map(item => item.id);    // n 的復(fù)雜度
const result = [];
minArrIdArr.map((id) => tempMaxArrObj[id] && result.push(tempMaxArrObj[id])); // min(m, n) 的復(fù)雜度。
2017年6月10日 02:33
編輯回答
墨小白
  for(var i = 0 ; i<arr1.length;i++){
        for(var j = 0 ; j<arr2.length;j++){
            if(arr1[i].id===arr2[j].id){
                console.log(arr1[i].name,arr2[j].name);
            }
        }
    }
2017年8月10日 01:24
編輯回答
厭遇
const concatArr = [...arr1, ...arr2]
const hash = {}
concatArr.forEach(obj => {
  if (hash[obj.id]) {
    // 這里就得到了兩個(gè)的 name 值:
    console.log(obj.name, hash[obj.id])
  } else {
    hash[obj.id] = obj.name
  }
})
2018年1月3日 09:54