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

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

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

Converting Object to an Array

Converting Object to an Array

Merge Array

How to combine two sorted arrays into one? We can do this easily with the spread operator.

How to reverse an Array?

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

flatMap()

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