在JavaScript中相交的多维数组

时间:2019-02-20 10:43:52

标签: javascript arrays intersection

假设我有1个多维数组,并且我想排除JavaScript中不相等的值。

这是示例数组。

var filter = ["big_number", "odds_number"];
var arrays = {
    "first" : {
        "big_number" : [50,51,52],
        "odds_number" : [39,41,51,53]
    },
    "second" : {
        "big_number" : [61,62,63,64,65,70,72,73],
        "odds_number" : [13,15,17,19,61,63,65,73]
    }
};

我想将该数组转换为这样。

var new_arrays = {
    "first" : [51],
    "second" : [61,63,65,73]
};

这是我的代码

var newArray = {
    "first" : [],
    "second" : []
};
for (var k in arrays){
    if (arrays.hasOwnProperty(k)) {
        for(var f=0; f<filter.length; f++) {
            newArray[k].push(arrays[k][filter[f]].filter(value => -1 !== arrays[k][filter[f]].indexOf(value))));
        }
   }
}
console.log(newArray);

实际上我可以执行这段代码

var newArray = {
    "first" : [],
    "second" : []
};
for (var k in arrays){
    if (arrays.hasOwnProperty(k)) {
        newArray[k].push(arrays[k]["big_number"].filter(value => -1 !== arrays[k]["odds_number"].indexOf(value))));
    }
}
console.log(newArray);

但是我需要通过filter variable进行转换。 我无法使用filter[0] and filter[1],因为该值可以动态更改,并且可能在数组中超过2个值。

4 个答案:

答案 0 :(得分:2)

您可以循环浏览键并使用filterincludes更新值:

var arrays={"first":{"big_number":[50,51,52],"odds_number":[39,41,51,53]},"second":{"big_number":[61,62,63,64,65,70,72,73],"odds_number":[13,15,17,19,61,63,65,73]}};

for (let key in arrays) {
  arrays[key] = arrays[key]["big_number"]
                  .filter(n => arrays[key]["odds_number"].includes(n));
}

console.log(arrays)

如果您不想变异原始对象,请使用Object.entriesreduce

var arrays={"first":{"big_number":[50,51,52],"odds_number":[39,41,51,53]},"second":{"big_number":[61,62,63,64,65,70,72,73],"odds_number":[13,15,17,19,61,63,65,73]}};

const newObject = Object.entries(arrays).reduce((r, [key, {big_number, odds_number}]) => {
  r[key] = big_number.filter(n => odds_number.includes(n));
  return r
}, {})

console.log(newObject)

如果具有两个以上的数组属性,则可以执行以下操作:使用Object.values获取所有数组,然后使用reduce递归运行前面的代码

var arrays = {
  "first": {
    "big_number": [50, 51, 52],
    "odds_number": [39, 41, 51, 53],
    "another_key": [41, 51, 53]
  },
  "second": {
    "big_number": [61, 62, 63, 64, 65, 70, 72, 73],
    "odds_number": [13, 15, 17, 19, 61, 63, 65, 73],
    "another_key": [63, 65]
  }
};

for (let key in arrays) {
  arrays[key] = Object.values(arrays[key])
                       .reduce((a, b) => a.filter(c => b.includes(c)))
}

console.log(arrays)

答案 1 :(得分:1)

这是一个小交叉片段:

function intersect(a,b){
    b.slice()
    return a.filter(item=>{
        if(b.includes(item)){
            b.splice(b.indexOf(item),1)
            return true
        }
    })
}

使用它,您可以轻松地做到这一点:

function intersect(a,b){
	b.slice()
	return a.filter(item=>{
		if(b.includes(item)){
			b.splice(b.indexOf(item),1)
			return true
		}
	})
}

var filter = ["big_number", "odds_number"];
var output={}
var arrays = {
    "first" : {
        "big_number" : [50,51,52],
        "odds_number" : [39,41,51,53]
    },
    "second" : {
        "big_number" : [61,62,63,64,65,70,72,73],
        "odds_number" : [13,15,17,19,61,63,65,73]
    }
};
for(x in arrays){
    output[x]=arrays[x][filter[0]]
    for(let i=1;i<filter.length;i++){
        output[x]=intersect(output[x],arrays[x][filter[i]])
    }
}
console.log (output) 

答案 2 :(得分:0)

使用Object.entries获取键和值,然后使用reduce

var arrays = {
  "first" : {
      "big_number" : [50,51,52],
      "odds_number" : [39,41,51,53]
  },
  "second" : {
      "big_number" : [61,62,63,64,65,70,72,73],
      "odds_number" : [13,15,17,19,61,63,65,73]
  }
};

const output =Object.entries(arrays).reduce((accu, [key, {big_number}]) => {
  if(!accu[key]) accu[key] = [];
  big_number.forEach(num => {
    if(num%2 !==0)
    accu[key].push(num);
  })
  return accu;
}, {});

console.log(output);

答案 3 :(得分:0)

您可以使用struct SearchResultData: Decodable { let server_response_time: Int let data: [SearchResultType] let success: Bool } struct SearchResultType: Decodable { let group: String let data: [Movie] } struct Movie: Decodable { let title: String? // this is nullable variable, } 从两个数组中获取唯一值,然后使用Set仅获取公共值。

filter
var arrays = {"first": {"big_number": [50, 51, 52],"odds_number": [39, 41, 51, 53]},"second": {"big_number": [61, 62, 63, 64, 65, 70, 72, 73],"odds_number": [13, 15, 17, 19, 61, 63, 65, 73]}},
    result = Object.keys(arrays).reduce((r,k) => {
      let setB = new Set(arrays[k]["big_number"]);
      r[k] = [...new Set(arrays[k]["odds_number"])].filter(x => setB.has(x));
      return r;
    },{});
console.log(result)