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

Convert Array-like to True Array

Convert Array-like to True Array

axios post await

Axios là một HTTP client được viết dựa trên Promises được dùng để hỗ trợ cho việc xây dựng các ứng dụng API từ đơn giản đến phức tạp. Có thể sử axios để post, get, put, delete...

Sử dụng reduce và concat làm phẳng một array

Array.reduce() và Array.concat() có thể giúp chúng ta làm phẳng một Array như:

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.