我试图比较不同值的两个数组并相应地过滤掉它们。我设法得到了孩子的过滤器价值我想要的。但是,我想知道是否有可能我也可以抓住父级阵列的过滤结果而不仅仅是孩子?
这是我的代码:
let arrayOne = {
smallBall: [
'randomball',
'anotherrandomball',
'bigball',
'smallball'
],
mediumBall: [
'mediumballsize',
'mediumsmallsizeball',
'randommediumball',
'anothermediumball'
]
}
let arrayTwo = {
smallBall: [
'randomball',
'anotherrandomball',
'bigballdifferent',
'smallballdifferent'
],
mediumBall: [
'mediumballsize',
'mediumsmallsizeball',
'randommediumballdifferent',
'anothermediumballdifferent'
]
}
// Loop through first Array
let firstnewArray = [];
for (var first in arrayOne) {
for (i = 0; i < arrayOne[first].length; i++) {
// Push the contents into a new array
firstnewArray.push(arrayOne[first][i]);
}
}
let secondnewArray = [];
for (var second in arrayTwo) {
for (i = 0; i < arrayTwo[second].length; i++) {
// Push the contents into a new array
secondnewArray.push(arrayTwo[second][i]);
}
}
let abDifference = firstnewArray.filter(x => secondnewArray.indexOf(x) == -1);
let baDifference = secondnewArray.filter(x => firstnewArray.indexOf(x) == -1);
// Original Arrays
console.log(firstnewArray);
console.log(secondnewArray);
// Filtered Results from new array that was pushed
console.log(abDifference);
console.log(baDifference);
答案 0 :(得分:1)
如果您希望结果看起来与原始对象(不是数组)相同,但是当它们同时出现时,嵌套项目会从中删除,那么您可以使用此功能:
function diff(a, b) {
const c = {};
for (const [key, arr] of Object.entries(a)) {
const filtered = arr.filter( s => !(b[key] && b[key].includes(s)) );
if (filtered.length) c[key] = filtered;
}
return c;
}
// Sample input
let arrayOne = {smallBall: ['randomball','anotherrandomball','bigball','smallball'],mediumBall:['mediumballsize','mediumsmallsizeball','randommediumball','anothermediumball']};
let arrayTwo = {smallBall: ['randomball','anotherrandomball','bigballdifferent','smallballdifferent'],mediumBall: ['mediumballsize','mediumsmallsizeball','randommediumballdifferent','anothermediumballdifferent']};
// Results
console.log(diff(arrayOne, arrayTwo));
console.log(diff(arrayTwo, arrayOne));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
@Thomas Junk的回答正是您所需要的。只需使用Object键修改两个数组即可。只需在过滤器逻辑之前添加此代码即可。
Object.keys(arrayOne).forEach(item => firstnewArray.push(item));
Object.keys(arrayTwo).forEach(item => secondnewArray.push(item));