Skip to content

Instantly share code, notes, and snippets.

@telekosmos
Last active December 26, 2025 08:37
Show Gist options
  • Select an option

  • Save telekosmos/3b62a31a5c43f40849bb to your computer and use it in GitHub Desktop.

Select an option

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)));
@VSmain

VSmain commented Jul 13, 2018

Copy link
Copy Markdown

do it with ladosh

const _ = require('lodash');
...
_.uniq([1,2,3,3,'a','a','x'])//1,2,3,'a','x'
_.uniqBy([{a:1,b:2},{a:1,b:2},{a:1,b:3}], v=>v.a.toString()+v.b.toString())//[{a:1,b:2},{a:1,b:3}]

@macmladen

Copy link
Copy Markdown

@mordentware I was puzzled with your results so I made a CodePen with my own data sample where I needed to remove duplicates.

Data array has 6.288 items, 5.284 of them are unique. Results are nearly the same for both sorted and unsorted arrays.

My findings are that filter and reduce are similar while Set was much faster. Reduce with spread was much slower due to a large number of deconstruction/construction.

See the Pen Deduplicating speed test by Mladen Đurić (@macmladen) on CodePen.

(times may vary due to system, browser, CPU, memory...)

Results on MacBook Pro i7 form 2011, using Firefox (usually with few hundred open tabs ;)

image

@joeyparrish

joeyparrish commented Sep 6, 2018

Copy link
Copy Markdown

Just discovered this thread and found that [0, 1, NaN, 3].indexOf(NaN) yields -1. :-( Probably because NaN != NaN.

Set dedups NaN correctly, though.

@nabilfreeman

Copy link
Copy Markdown

Set is so cool! Never knew it existed!

@joshuapinter

Copy link
Copy Markdown

As with @VSmain, I'm tossing Lodash into the ring:

import _ from "lodash";

_.uniq([2, 1, 2]);
// => [2, 1]

Documentation on uniq.

@impfromliga

Copy link
Copy Markdown

Set is shorter but filter with indexof is faster. example

it's just because the better complexity will faster on bigger counts. And be faster greatly be on them, instead of 10 elements array...
you have to check it at least on hundreds

@brunoandradebr

Copy link
Copy Markdown

If you need to filter by object value and a performance way :

// creates an object only once - garbage be glad ^^
let cachedObject = {};

// array to be filtered
let arr = [
    {id : 0, prop : 'blah'},
    {id : 1, prop : 'foo'},
    {id : 0, prop : 'bar'}
]

// "filter" to object - keep original array - garbage be glad too ^^
arr.map((item)=> cachedObject[item.id] = item)

// optional, turns object to array
arr = Object.values(cachedObject)

@Kr3m

Kr3m commented Feb 8, 2019

Copy link
Copy Markdown

What's wrong with

let arr1 = ["apples", "apples", "oranges", "bananas"]; arr1 = Array.from(new Set(arr1));

Surely this is a lot simpler if you're just trying to remove duplicates. Obviously this would work better as the return statement in a function. I'm just posting this as an example.

@little-brother

Copy link
Copy Markdown
let arr = [1, 2, 3, 4, 3, 2];
arr.filter((e, i, arr) => arr.indexOf(e) == i);

let arr = [{x:10, y: 20}, {x:10, y: 30}, {x:10, y: 20}]; // each element has x and y props
arr.filter((e, i, arr) => arr.findIndex(e2 => Object.keys(e2).every(prop => e2[prop] == e[prop])) == i);

@philihp

philihp commented Feb 26, 2019

Copy link
Copy Markdown

I find this reads a little bit better if you stash your reducer function in a named variable.

const duplicates = (e, i, arr) => arr.indexOf(e) === i

let arr = [1, 2, 3, 4, 3, 2];
arr.filter(duplicates);

@indatawetrust

indatawetrust commented Mar 15, 2019

Copy link
Copy Markdown
Array.prototype.uniq = function(key) {
  return key
    ? this.map(e => e[key])
        .map((e, i, final) => final.indexOf(e) === i && i)
        .filter(e => this[e])
        .map(e => this[e])
    : [...new Set(this)];
}

@patrickmichalina

patrickmichalina commented Mar 16, 2019

Copy link
Copy Markdown

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
Copy Markdown

Find brief article here : Click here to view

@fosteev

fosteev commented Mar 10, 2020

Copy link
Copy Markdown

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

@ioness

ioness commented Apr 27, 2020

Copy link
Copy Markdown

Excelent, thanks!

@gevera

gevera commented Nov 15, 2022

Copy link
Copy Markdown
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
Copy Markdown

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