Get all unique values in a JavaScript array (remove duplicates)
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']
Get all unique values in a JavaScript array (remove duplicates)
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']
Remove duplicate values from JS array
Quick and dirty using jQuery:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
Filter array to have unique values
You can use Array.filter function to filter out elements of an array based on the return value of a callback function. The callback function runs for every element of the original array.
The logic for the callback function here is that if the indexOf
value for current item is same as the index, it means the element has been encountered first time, so it can be considered unique. If not, it means the element has been encountered already, so should be discarded now.
var arr = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"];
var filteredArray = arr.filter(function(item, pos){ return arr.indexOf(item)== pos; });
console.log( filteredArray );
How to get unique values in an array
Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains
and unique
Array.prototype.contains = function(v) { for (var i = 0; i < this.length; i++) { if (this[i] === v) return true; } return false;};
Array.prototype.unique = function() { var arr = []; for (var i = 0; i < this.length; i++) { if (!arr.contains(this[i])) { arr.push(this[i]); } } return arr;}
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];var uniques = duplicates.unique(); // result = [1,3,4,2,8]
console.log(uniques);
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):
const findDuplicates = (arr) => { let sorted_arr = arr.slice().sort(); // You can define the comparing function here. // JS by default uses a crappy string compare. // (we use slice to clone the array so the // original array won't be modified) let results = []; for (let i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results;}
let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
Get unique values from array of arrays
You can use .flat()
to flatten your array and then use Set
to get its unique values.
Demo:
let arr = [ [ "s1@example.com", "s2@example.com" ], [ "s1@example.com", "s3@example.com" ]]
let arr2 = [...new Set(arr.flat(1))];console.log(arr2)
How to get all unique objects (with two values) in an array?
We can use Array.reduce(),
along with a Map to get the required result.
We'd add each item to the map, using the concatenated x and y values as keys, then return the values() to get de-duplicated values.
This will have complexity of O(n), so it will be efficient for large arrays.
const coords = [{x: 260, y: 60}, {x: 180, y: 0}, {x: 180, y: 240}, {x: 360, y: 120}, {x: 180, y: 60}, {x: 180, y: 60}, {x: 180, y: 60}];
const dedup = [...coords.reduce((map, { x, y }) => {
return (map.set(`${x}-${y}`, { x, y }));
}, new Map()).values()];
console.log('De-duplicated:', dedup)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Get all unique values in a JavaScript array (remove duplicates)
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']
How to remove all duplicates from an array of objects?
A primitive method would be:
const obj = {};
for (let i = 0, len = things.thing.length; i < len; i++) {
obj[things.thing[i]['place']] = things.thing[i];
}
things.thing = new Array();
for (const key in obj) {
things.thing.push(obj[key]);
}
Related Topics
Should CSS Always Precede JavaScript
Why Is Document.Write Considered a "Bad Practice"
Webkit-Based Blurry/Distorted Text Post-Animation Via Translate3D
Modifying CSS Class Property Values on the Fly With JavaScript/Jquery
How to Add Multiple Classes to a Reactjs Component
Access CSS Variable from JavaScript
How to Show Popup Message Like in Stack Overflow
Compare Two Dates With JavaScript
For-Each Over an Array in JavaScript
How to Use a Variable For a Key in a JavaScript Object Literal
How to Deal With Floating Point Number Precision in JavaScript
Detect Change in Orientation Using JavaScript
Get the Values from the "Get" Parameters (JavaScript)
Open a Url in a New Tab (And Not a New Window)
Disable Same Origin Policy in Chrome
Run JavaScript Function When User Finishes Typing Instead of on Key Up
Force Link to Open in Mobile Safari from a Web App With JavaScript