gpt4 book ai didi

javascript - 比较对象值并返回新数组

转载 作者:行者123 更新时间:2023-11-30 11:07:00 24 4
gpt4 key购买 nike

我有这两个数组:

const data = [ 
{ type: 'type1', location: 23 },
{ type: 'type2', location: 37 },
{ type: 'type3', location: 61 },
{ type: 'type4', location: 67 }
]

const com = [
{ name: "com1", location: 36 },
{ name: "com2", location: 60 }
]

我想测试 com +1 数组中的 locationComment 是否等于 data 数组中的 locationMethod ,如果是,那么我想要这样的东西:

const array = [
{type: 'type2', name: "com1"},
{type: 'type3', name: "com2"}
]

这是我的代码:

const result = data.map((x)=>{
const arr = [];
com.map((y)=>{
if(x.location == y.location+1){
arr.push({
type: x.type,
name: y.name,
location: x.location
})
}
})
return arr;
});

这是我得到的输出:

[ [],
[ { type: 'type2', name: 'com1', location: 37 } ],
[ { type: 'type3', name: 'com2', location: 61 } ],
[] ]

最佳答案

因为您不确定 com 数组中的每个元素是否都会匹配,所以您应该使用 reduce:

const data = [ 
{ type: 'type1', location: 23 },
{ type: 'type2', location: 37 },
{ type: 'type3', location: 61 },
{ type: 'type4', location: 67 }
];

const com = [
{ name: "com1", location: 36 },
{ name: "com2", location: 60 }
];

const output = com.reduce((a, { name, location }) => {
const found = data.find(item => item.location === location + 1);
if (found) {
a.push({ type: found.type, name });
}
return a;
}, []);
console.log(output);

如果 location 是唯一的,您可以通过将 data 转换为由 索引的对象来将时间复杂度降低到 O(N) code>location 第一:

const data = [ 
{ type: 'type1', location: 23 },
{ type: 'type2', location: 37 },
{ type: 'type3', location: 61 },
{ type: 'type4', location: 67 }
];

const com = [
{ name: "com1", location: 36 },
{ name: "com2", location: 60 }
];

const dataByLoc = data.reduce((a, item) => {
a[item.location] = item;
return a;
}, {});

const output = com.reduce((a, { name, location }) => {
const found = dataByLoc[location + 1];
if (found) {
a.push({ type: found.type, name });
}
return a;
}, []);
console.log(output);

关于javascript - 比较对象值并返回新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com