array1 = [
{id: 1, height: 178}, {id: 1, height: 176},
{id: 2, height: 168},{id: 2, height: 164}
]
array2 = [
{id: 1, height: ''},{id: 1, height: ''},
{id: 2, height: ''},{id: 2, height: ''},
{id: 3, height: ''}, {id: 3, height: ''},
{id: 4, height: ''}, {id: 4, height: ''}
]
resultArray = [
{id: 1, height: 178},{id: 1, height: 176},
{id: 2, height: 168},{id: 2, height: 164},
{id: 3, height:''}, {id: 3, height: ''},
{id: 4, height: ''}, {id: 4, height: ''}
]
我希望将array1
的ID与array2
的ID进行比较,如果array1
中缺少任何对象,则将其添加到该数组中。你能建议我怎么做吗?
谢谢
答案 0 :(得分:2)
我建议使用一组array1
的键进行快速查找。请注意,这会使array1
发生变化:
const array1 = [{id: 1, height: 178},{id: 1, height: 176},{id: 2, height: 168},{id: 2, height: 164}]
const array2 = [{id: 1, height: ''},{id: 1, height: ''},{id: 2, height: ''},{id: 2, height: ''}, {id: 3, height: ''}, {id: 3, height: ''}, {id: 4, height: ''}, {id: 4, height: ''}]
const ids = new Set(array1.map(e => e.id));
array2.forEach(e => {
if (!ids.has(e.id)) {
array1.push(e);
}
});
console.log(array1);
答案 1 :(得分:0)
1-保存第一个数组的长度
2-遍历第二个数组项
3-如果id不存在或其索引大于数组的长度,则将项目推到第一个数组。
let array1 = [{ id: 1, height: 178 }, { id: 1, height: 176 }, { id: 2, height: 168 }, { id: 2, height: 164 }], array2 = [{ id: 1, height: '' }, { id: 1, height: '' }, { id: 2, height: '' }, { id: 2, height: '' }, { id: 3, height: '' }, { id: 3, height: '' }, { id: 4, height: '' }, { id: 4, height: '' }],
arr1Length = array1.length;
array2.forEach(function(itm) {
let index = array1.findIndex(function(it) {
return it.id == itm.id;
});
if (-1 == index || arr1Length <= index) {
array1.push(itm)
}
});
console.log(array1)
答案 2 :(得分:0)
id
或Set
之类的东西,从array1
中创建一个Array.prototype.reduce()
个属性,Array.prototype.map()
个array2
中过滤掉不在Set
中的条目array1
与过滤后的结果连接起来
const array1 = [{id: 1, height: 178},{id: 1, height: 176},{id: 2, height: 168},{id: 2, height: 164}]
const array2 = [{id: 1, height: ''},{id: 1, height: ''},{id: 2, height: ''},{id: 2, height: ''}, {id: 3, height: ''}, {id: 3, height: ''}, {id: 4, height: ''}, {id: 4, height: ''}]
// Step #1
const knownIds = array1.reduce((set, {id}) => set.add(id), new Set())
// Steps 2 and 3
const resultArray = array1.concat(array2.filter(({id}) => !knownIds.has(id)))
console.info(resultArray)