Skip to content

Instantly share code, notes, and snippets.

@telekosmos
Last active November 15, 2022 17:13
Show Gist options
  • Save telekosmos/3b62a31a5c43f40849bb to your computer and use it in GitHub Desktop.
Save telekosmos/3b62a31a5c43f40849bb to your computer and use it in GitHub Desktop.
Remove duplicates from js array (ES5/ES6)
var uniqueArray = function(arrArg) {
return arrArg.filter(function(elem, pos,arr) {
return arr.indexOf(elem) == pos;
});
};
var uniqEs6 = (arrArg) => {
return arrArg.filter((elem, pos, arr) => {
return arr.indexOf(elem) == pos;
});
}
var test = ['mike','james','james','alex'];
var testBis = ['alex', 'yuri', 'jabari'];
console.log(uniqueArray(test.concat(testBis)));
@patrickmichalina
Copy link

patrickmichalina commented Mar 16, 2019

In Typescript

export const dedupeByProperty =
  <T>(arr: ReadonlyArray<T>, objKey: keyof T) =>
    arr.reduce<ReadonlyArray<T>>((acc, curr) =>
      acc.some(a => a[objKey] === curr[objKey])
        ? acc
        : [...acc, curr], [])

@pankajkrr
Copy link

Find brief article here : Click here to view

@fosteev
Copy link

fosteev commented Mar 10, 2020

const uniq = elements.reduce((acc, value) => acc.some(i => i.id === value.id) ? acc : acc.concat(value), []); // id your uniq key

@ioness
Copy link

ioness commented Apr 27, 2020

Excelent, thanks!

@gevera
Copy link

gevera commented Nov 15, 2022

const deduplicateArrays = ( arr1, arr2 = [] ) => [
...new Set([
           ...arr1.map(i => JSON.stringify(i)),
           ...arr2.map(i => JSON.stringify(i))
          ])
].map(i => JSON.parse(i))

@guillaumegarcia13
Copy link

Hi @gevera
Beware of problems when using JSON.stringify and JSON.parse with:

Being bitten more than once... 🤕

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment