How to compare two different arrays which has different property names and remove unmatched ones in javascript?

I havve two different arrays with different property names like below

arrayA = [
    { id: 20, name: 'Jason' },
    { id: 15, name: 'Harry' },
    { id: 5, name: 'Clara' },
    { id: 9, name: 'Melonie' }
]

arrayB = [
    { courseID: 12, studentID: 20 },
    { courseID: 12, studentID: 15 }
]

I want to compare these two different arrays and remove unmatched ids from arrayA. For comparison, id field of arrayA and studentID field of arrayB matters. if these fileds aren't equal to each other, they should be removed from arrayA.

Expected is below

arrayA = [{id: 20, name: 'Jason' }, { id: 15, name: 'Harry' }]

Here is what I tried below but didn't work. Gave me empty array.

filteredElements = this.arrayA.map(e => e.id).filter(
    val => this.arrayB.indexOf(val.studentID) !== -1
);

Upvotes: 1

Views: 52

Answers (4)

Ben Aston
Ben Aston

Reputation: 55729

Create a dictionary from courseMembers, keyed on studentID, to enable O(1) lookup.

Filter students according to the dictionary.

const students = [{id:20,name:'Jason'},{id:15,name:'Harry'},{id:5,name:'Clara'},{id:9,name:'Melonie'}]
const courseMembers = [{courseID:12,studentID:20},{courseID:12,studentID:15}]

function withCourses(students, courseMembers) {
    const map = courseMembers.reduce((acc, {studentID}) => 
        (acc[studentID] = true, acc), {})
    return students.filter(({id}) => map[id])
}
const result = withCourses(students, courseMembers)
console.log(result) // [{ id:20, name:"Jason" },{ id:15, name:"Harry" }]

Upvotes: 0

M A Salman
M A Salman

Reputation: 3820

let arrayA = [{id: 20,name: 'Jason'},{id: 15,name: 'Harry'},{id: 5,name: 'Clara'},{id: 9,name: 'Melonie'}]
let arrayB = [{courseID: 12,studentID: 20},{courseID: 12,studentID: 15}];
let filtered=arrayA.filter(obj =>{ if(arrayB.find(course => course.studentID == obj.id))return true;return false;
});
console.log(filtered);

Upvotes: 1

saulotoledo
saulotoledo

Reputation: 1972

Try this:

var studentIds = arrayB.map(course => course.studentID);
var result = arrayA.filter(student => studentIds.includes(student.id));

The variable result contains your result.

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36564

You can do that in following steps:

  • Use map() on arrayB and create array of courseID.
  • Then create a Set() from that Array
  • Then use filter() arrayA and check whether id of object exists in above created Set or not using Set.prototype.has()

const arrayA = [{id:20,name:'Jason'},{id:15,name:'Harry'},{id:5,name:'Clara'},{id:9,name:'Melonie'}]
const arrayB =[{courseID:12,studentID:20},{courseID:12,studentID:15}];
const ids = new Set(arrayB.map(x => x.studentID));
const res = arrayA.filter(x => ids.has(x.id));
console.log(res);

Upvotes: 1

Related Questions