Skip to content
On this page

数组去重

普通数组

js
const arr = [1, 2, 3, 1, 2, 3];
function unique(arr) {
  return Array.from(new Set(arr));
}
console.log(unique(arr)); // [1, 2, 3]

对象数组

js
const arr = [
  { id: 1, value: "a" },
  { id: 2, value: "aa" },
  { id: 1, value: "a" },
  { id: 2, value: "aa" },
];
function unique(arr) {
  const set = new Set(arr.map((item) => JSON.stringify(item)));
  return [...set].map((item) => JSON.parse(item));
}
console.log(unique(arr)); // [{ id: 1, value: "a" },{ id: 2, value: "aa" }]

Released under the MIT License.