Kiểm tra phần tử trùng trong mảng JavaScript

map,array,web_developer

Kiểm tra phần tử trùng trong mảng JavaScript.

const arr = [
 { id: 1, name: "king" },
 { id: 2, name: "master" },
 { id: 3, name: "lisa" },
 { id: 4, name: "ion" },
 { id: 5, name: "jim" },
 { id: 6, name: "gowtham" },
 { id: 1, name: "jam" },
 { id: 1, name: "lol" },
 { id: 2, name: "kwick" },
 { id: 3, name: "april" },
 { id: 7, name: "sss" },
 { id: 8, name: "brace" },
 { id: 8, name: "peiter" },
 { id: 5, name: "hey" },
 { id: 6, name: "mkl" },
 { id: 9, name: "melast" },
 { id: 9, name: "imlast" },
 { id: 10, name: "glow" }
]

function getUnique(arr, comp) {

 const unique = arr
 .map(e => e[comp])

 // store the keys of the unique objects
 .map((e, i, final) => final.indexOf(e) === i && i)

 // eliminate the dead keys & store unique objects
 .filter(e => arr[e]).map(e => arr[e]);

 return unique;
}

console.log(getUnique(arr,'id'); //[{"id":1,"name":"king"},{"id":2,"name":"master"},{"id":3,"name":"lisa"},{"id":4,"name":"ion"},{"id":5,"name":"jim"},{"id":6,"name":"gowtham"},{"id":7,"name":"sss"},{"id":8,"name":"brace"},{"id":9,"name":"melast"},{"id":10,"name":"glow"}]

Có thể bạn đã miss một số snippets code

Converting Object to an Array

Converting Object to an Array

Remove array of objects from another array of objects

Remove array of objects from another array of objects

Filter Unique Values

Kiểu đối tượng Set đã được giới thiệu trong ES6 và cùng với ..., ‘spread’ operator, chúng ta có thể sử dụng nó để tạo một mảng mới chỉ với các giá trị duy nhất.

flatMap()

Use flatMap() creates a new array with sub-array elements flattened by specified depth.

How to reverse an Array?

Reversing an array in JS is really simple with the standard array method. Like below