Adakah cara lain yg lebih baik untuk remove duplicate object dalam array seperti ini?

let students = [
  {
    studentID: 1,
    name: 'Irman',
  },
  {
    studentID: 1,
    name: 'Irman',
  },
  {
    studentID: 2,
    name: 'Supri',
  },
  {
    studentID: 5,
    name: 'Budi',
  }
];

let studentId = [];
let differentStudents = [];

for (let item of students) {
  if (!studentId.includes(item.studentID)) {
    differentStudents.push(item);
    studentId.push(item.studentID);
  }
}
avatar iamfreestyler
@iamfreestyler

341 Kontribusi 57 Poin

Diperbarui 4 tahun yang lalu

2 Jawaban:

<div>Menggunakan filter untuk unique berdasarkan id nya</div><pre>arr.filter((v,i,a) =&gt; a.findIndex(t=&gt;(t.id === v.id))===i)</pre><div><br><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">refrensi filter javascript</a><br><br>Di es6+</div><pre>const unique = [...new Map(arr.map(item =&gt; [item[key], item])).values()]</pre><div><br>Jawaban dari stackoverflow: <a href="https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript">remove duplicate from object javascript</a></div><div><br><br></div>

avatar hilmanski
@hilmanski

2685 Kontribusi 2135 Poin

Dipost 4 tahun yang lalu

Tanggapan

Terimakasih banyak jawabannya bang hilman

<div>tambahan saja.<br><br>dengan <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set</a></div><pre>let uniqueBySet = [...new Set(students.map(v =&gt; v.studentID))].map(v =&gt; students.find(({studentID}) =&gt; studentID === v));</pre><div><br>dengan <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">reduce</a></div><pre>let uniqueByReduce = students.reduce((pv, cv) =&gt; pv.some(v =&gt; v.studentID === cv.studentID) ? pv : [...pv, cv], []);</pre>

avatar soeleman
@soeleman

120 Kontribusi 147 Poin

Dipost 4 tahun yang lalu

Login untuk ikut Jawaban