Postingan lainnya
Kelas Premium!
Belajar Javascript untuk website
Gunakan kupon "mulaijs" untuk diskon 75 ribu!
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);
}
}
2 Jawaban:
<div>Menggunakan filter untuk unique berdasarkan id nya</div><pre>arr.filter((v,i,a) => a.findIndex(t=>(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 => [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>
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 => v.studentID))].map(v => students.find(({studentID}) => 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) => pv.some(v => v.studentID === cv.studentID) ? pv : [...pv, cv], []);</pre>