-2

how to merge this array without duplicate?

students1=[{studentId: "0001", name: "Joe", class: "1"},{studentId: "0002", name: "john", class: "1"},{studentId: "0003", name: "Max", class: "1"}];

students2=[{studentId: "0001", name: "Joe", class: "1"},{studentId: "0002", name: "john", class: "1"},{studentId: "0003", name: "Max", class: "1"},{studentId: "0004", name: "Jony", class: "1"}];

allStudents=$.merge(students1,students2);
vijay
  • 244
  • 4
  • 16
  • 1
    did you google it? *How to remove duplicates from array?* – Rajesh Jan 29 '18 at 05:19
  • 2
    Possible Duplicate: https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items – Rajesh Jan 29 '18 at 05:21
  • Possible duplicate of [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Aluan Haddad Apr 24 '18 at 04:40

1 Answers1

3

You can array#concat both arrays and then use array#reduce to get the unique values from both arrays.

const students1=[{studentId: "0001", name: "Joe", class: "1"},{studentId: "0002", name: "john", class: "1"},{studentId: "0003", name: "Max", class: "1"}],
      students2=[{studentId: "0001", name: "Joe", class: "1"},{studentId: "0002", name: "john", class: "1"},{studentId: "0003", name: "Max", class: "1"},{studentId: "0004", name: "Jony", class: "1"}],
      allstudents = Object.values(students1.concat(students2).reduce((r,o) => {
        r[o.studentId] = o;
        return r;
      },{}));
console.log(allstudents);
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51