09 June 2018

Javascript: Xóa phần tử trùng nhau trong mảng (Array Object) Javascript - Remove Duplicates from an Array

Xóa các bản ghi giống nhau khỏi một mảng
Javascript 2018
<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>Remove duplicates array of objects</h2>
<button type="button" onclick="loadDoc1()">Change Array String</button>
<button type="button" onclick="loadDoc2()">Change Array Object</button>
</div>

<script>
function loadDoc1() {
   const list = ['John', 'Paul', 'George', 'Ringo', 'John'];
   console.log("List");
   console.log(list);
 
   let x = list.filter((v,i) => list.indexOf(v) === i)

   console.log("Remove duplicates array");
   console.log(x);
}
function loadDoc2() {
   const list = [{ name: 'John', value: 'Ringo'}, { name: 'John', value: "Ringo"}, { name: 'Anotnio', value: "as3a123s"}, { name: 'Anotnio', value: "asda4s"}];
   console.log("List");
   console.log(list);
 
   var x = Array.from(new Set(list.map(JSON.stringify))).map(JSON.parse);

   console.log("Remove duplicates array of objects");
   console.log(x)
}
</script>

</body>
</html>

ES6 Typescript Remove Duplicates from an Array
2018 Typescript
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" }
];

public 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')

Remove duplicates array of objects



0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang