Skip to content
Fix Code Error

Get all unique values in a JavaScript array (remove duplicates)

March 13, 2021 by Code Error
Posted By: Anonymous

I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found this other script here on Stack Overflow that looks almost exactly like it, but it doesn’t fail.

So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong?

Array.prototype.getUnique = function() {
 var o = {}, a = [], i, e;
 for (i = 0; e = this[i]; i++) {o[e] = 1};
 for (e in o) {a.push (e)};
 return a;
}

More answers from duplicate question:

  • Remove duplicate values from JS array

Similar question:

  • Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Solution

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values:

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique);

console.log(unique); // ['a', 1, 2, '1']

The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.

onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.

This solution works without any extra library like jQuery or prototype.js.

It works for arrays with mixed value types too.

For old Browsers (<ie9), that do not support the native methods filter and indexOf you can find work arounds in the MDN documentation for filter and indexOf.

If you want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf.

With ES6 it could be shorten to this:

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i);

console.log(unique); // unique is ['a', 1, 2, '1']

Thanks to Camilo Martin for hint in comment.

ES6 has a native object Set to store unique values. To get an array with unique values you could do now this:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)];

console.log(unique); // unique is ['a', 1, 2, '1']

The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array. Thanks to Lukas Liese for hint in comment.

Answered By: Anonymous

Related Articles

  • Use of Jquery on scroll event
  • How do I include certain conditions in SQL Count
  • Is it possible to apply CSS to half of a character?
  • For-each over an array in JavaScript
  • How to "properly" create a custom object in JavaScript?
  • How do I keep only the first map and when the game…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • What does this symbol mean in JavaScript?
  • How do I style a dropdown with only CSS?
  • How does JavaScript .prototype work?
  • pyspark window function from current row to a row…
  • What does do?
  • Smart way to truncate long strings
  • What is the 'new' keyword in JavaScript?
  • Reference - What does this regex mean?
  • Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM
  • Centering in CSS Grid
  • What is the scope of variables in JavaScript?
  • Why does C++ code for testing the Collatz conjecture…
  • Adobe XD to responsive html
  • JavaScript gives NaN error on the page but variable…
  • Finding all possible combinations of numbers to…
  • How to filter a RecyclerView with a SearchView
  • How do JavaScript closures work?
  • Sort table rows In Bootstrap
  • Java Array, Finding Duplicates
  • Active tab issue on page load HTML
  • Running Internet Explorer 6, Internet Explorer 7,…
  • Ukkonen's suffix tree algorithm in plain English
  • C compile error: Id returned 1 exit status
  • How to remove element from array in forEach loop?
  • Regular expression to match numbers with or without…
  • Coffeescript class extend more bloat than Backbone extend
  • SQL query return data from multiple tables
  • TypeScript metadata reflection references other…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Not submit any value if checkbox is empty
  • Get the name of an object's type
  • How does the "this" keyword work?
  • Identifying and solving…
  • setTimeout function not working : javascript
  • Memcached vs. Redis?
  • explain backbone object and class creation pattern
  • Typeerror: n is undefined in underscore.min.js
  • How to find out what is referencing a detached DOM…
  • Creating an index on a table variable
  • How do I return the response from an asynchronous call?
  • In CSS Flexbox, why are there no "justify-items" and…
  • Maximum XOR With an Element From Array | Leetcode
  • how to use canvas in JavaScript flappy bird code
  • Easy interview question got harder: given numbers…
  • How can I pass a wct test while rearranging children…
  • Class vs. static method in JavaScript
  • Do you (really) write exception safe code?
  • Make Iframe to fit 100% of container's remaining height
  • Chrome / Safari not filling 100% height of flex parent
  • JavaScript hashmap equivalent
  • Getting started with Haskell
  • CSS overflow-x: visible; and overflow-y: hidden;…
  • commandButton/commandLink/ajax action/listener…
  • data.table vs dplyr: can one do something well the…
  • How do I resolve `The following packages have unmet…
  • (SETF L (FLATTEN L)) should be a lambda expression error
  • How can I parse a CSV string with JavaScript, which…
  • Find duplicate values in R
  • Why my "title" bloc doesn't go to bottom?
  • Why doesn't the height of a container element…
  • RegEx match open tags except XHTML self-contained tags
  • Show/hide 'div' using JavaScript
  • jQuery Mobile: document ready vs. page events
  • How do Mockito matchers work?
  • How to use html template with vue.js
  • Animating Elements in One by One
  • Remove all child elements of a DOM node in JavaScript
  • Aurelia Getting Repeat.for converted array length…
  • Undefined reference to 'vtable for ✘✘✘'
  • center 3 items on 2 lines
  • What's the most efficient way to erase duplicates…
  • What methods of ‘clearfix’ can I use?
  • Dynamic reactive objects conflits with observe…
  • How to dynamically add and remove views with Ember.js
  • Determine if string is in list in JavaScript
  • Why is this inline-block element pushed downward?
  • ExpressJS How to structure an application?
  • Backbone.js: TypeError: Object # has no method 'parse'
  • How does PHP 'foreach' actually work?
  • I want to solve the javascript OOP problems, but my…
  • SecurityException: Permission denied (missing…
  • How to merge two arrays in JavaScript and de-duplicate items
  • Make div (height) occupy parent remaining height
  • What are the nuances of scope prototypal /…
  • Using Auto Layout in UITableView for dynamic cell…
  • Replace duplicates in matrix
  • What is a plain English explanation of "Big O" notation?
  • How to check internet access on Android? InetAddress…
  • Validate that a string is a positive integer
  • How to implement a basic iterative pushdown…
  • JavaScript OOP in NodeJS: how?
  • Fastest way to list all primes below N
  • Can I run javascript before the whole page is loaded?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I replace a newline (n) using sed?

Next Post:

Hiding the scroll bar on an HTML page

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error