- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Any way to solve this without concatenating these two arrays to get objects with higher value?
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 } ]
Advertisements