To get objects with specific property, use the concept of reduce() on both arrays individually. You don’t need to concatenate. Let’s say the following are our objects with student name and student marks
var sectionAStudentDetails = [ {studentName: 'John', studentMarks: 78}, {studentName: 'David', studentMarks: 65}, {studentName: 'Bob', studentMarks: 98} ]; let sectionBStudentDetails = [ {studentName: 'John', studentMarks: 67}, {studentName: 'David', studentMarks: 89}, {studentName: 'Bob', studentMarks: 97} ];
Following is the code to implement reduce() on both and fetch the object with higher value (marks) −
Example
var sectionAStudentDetails = [ {studentName: 'John', studentMarks: 78}, {studentName: 'David', studentMarks: 65}, {studentName: 'Bob', studentMarks: 98} ]; let sectionBStudentDetails = [ {studentName: 'John', studentMarks: 67}, {studentName: 'David', studentMarks: 89}, {studentName: 'Bob', studentMarks: 97} ]; function concatTwoArraysWithoutConcatFunction(arrayValues, k) { const previousValue = arrayValues[k.studentName]; if (!previousValue || k.studentMarks >= previousValue.studentMarks) arrayValues[k.studentName] = k; return arrayValues; } const setionA = sectionAStudentDetails.reduce(concatTwoArraysWithoutConcatFunction, {}); const sectionB = sectionBStudentDetails.reduce(concatTwoArraysWithoutConcatFunction, setionA); console.log(Object.values(sectionB));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo84.js.
Output
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo84.js [ { studentName: 'John', studentMarks: 78 }, { studentName: 'David', studentMarks: 89 }, { studentName: 'Bob', studentMarks: 98 } ]