What's the efficient way to iterate through 2 arrays of Objects and return a single array of objects?
I want to iterate through the exerxises array, compare each object.id with searchResult's object.id and return non-equal searchResult objects in a new array without duplicate.
I'm having issues because both arrays are not of the same length
const exercises = [
{
id: 'pull-ups',
title: 'Pull Ups',
description: 'Back and biceps exercise...',
muscles: 'back'
},
{
id: 'deadlifts',
title: 'Deadlifts',
description: 'Back and leg exercise...',
muscles: 'back'
},
{
id: 'squats',
title: 'Squats',
description: 'Legs exercise...',
muscles: 'legs'
}
]
const searchResult = [
{
id: 'overhead-press',
title: 'Overhead Press',
description: 'Delts exercise...',
muscles: 'shoulders'
},
{
id: 'dips',
title: 'Dips',
description: 'Triceps exercise...',
muscles: 'arms'
},
{
id: 'barbell-curls',
title: 'Barbell Curls',
description: 'Biceps exercise...',
muscles: 'arms'
},
{
id: 'bench-press',
title: 'Bench Press',
description: 'Chest exercise...',
muscles: 'chest'
},
{
id: 'pull-ups',
title: 'Pull Ups',
description: 'Back and biceps exercise...',
muscles: 'back'
},
{
id: 'deadlifts',
title: 'Deadlifts',
description: 'Back and leg exercise...',
muscles: 'back'
},
{
id: 'squats',
title: 'Squats',
description: 'Legs exercise...',
muscles: 'legs'
}
]
by comparing the ids, I want to return a new array of Objects from the difference btw exercises and searchResult without duplicates!
const exercises = [{id: 'pull-ups',title: 'Pull Ups',description: 'Back and biceps exercise...',muscles: 'back'},
{id: 'deadlifts',title: 'Deadlifts',description: 'Back and leg exercise...',muscles: 'back'},
{id: 'squats',title: 'Squats',description: 'Legs exercise...',muscles: 'legs'}]
const searchResult = [{id: 'overhead-press',title: 'Overhead Press',description: 'Delts exercise...',muscles: 'shoulders'},
{id: 'dips',title: 'Dips',description: 'Triceps exercise...',muscles: 'arms'},
{id: 'barbell-curls',title: 'Barbell Curls',description: 'Biceps exercise...',muscles: 'arms'},
{id: 'bench-press',title: 'Bench Press',description: 'Chest exercise...',muscles: 'chest'},
{id: 'pull-ups',title: 'Pull Ups',description: 'Back and biceps exercise...',muscles: 'back'},
{id: 'deadlifts',title: 'Deadlifts',description: 'Back and leg exercise...',muscles: 'back'},
{id: 'squats',title: 'Squats',description: 'Legs exercise...',muscles: 'legs'}]
let op = searchResult.reduce((op,inp) => {
let add = exercises.find(e=> e.id === inp.id)
if(!add){
op[inp.id] = inp
}
return op
},{})
console.log(Object.values(op))