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 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 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)
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 );
Getting unique values from an Array for use in ListItem
Edit I misunderstood the question, I would suggest using reduce
.
note I made all require
statements a string for this example to run
const Users = [{
id: 1,
name: "user1",
image: 'require("../assets/1.jpeg")',
location: "Portland"
},
{
id: 2,
name: "user2",
image: 'require("../assets/2.jpeg")',
location: "Portland"
},
{
id: 3,
name: "user3",
image: 'require("../assets/3.jpeg")',
location: "New York"
},
{
id: 4,
name: "user4",
image: 'require("../assets/4.jpeg")',
location: "Pullman"
},
{
id: 5,
name: "user5",
image: 'require("../assets/5.jpeg")',
location: "Portland"
},
{
id: 6,
name: "user6",
image: 'require("../assets/6.jpeg")',
location: "San Francisco"
},
{
id: 7,
name: "user7",
image: 'require("../assets/7.jpeg")',
location: "Pullman"
},
];
console.log(Users.reduce((acc, val) => {
acc[val.location] = acc[val.location] ? [...acc[val.location], val] : [val];
return acc
}, {}))
Get unique values of a Javascript array
You are almost there.
splice() method's first parameter is the start index, the index at which to start changing the array.
In your code, vector.splice(vector[indexRepeated[i]], 1, null);
you are passing the value at that index in vector
array instead of that index. That is the reason for unexpected output.
Just change that line to vector.splice(indexRepeated[i], 1, null);
and filter null
values.
Live Example:
function uniqueArrayValues(vector) { var indexRepeated = []; for (let i in vector) { for (let j in vector) { if (vector[i] == vector[j] && i != j && j != null && i != null && i < j) { indexRepeated.push(j); } }
for (let i in indexRepeated) { if (vector[indexRepeated[i]] != null) { vector.splice(indexRepeated[i], 1, null); } } } return vector.filter(value => value !== null); // Can also use vector.filter(value => value);}
var arr = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5];
console.log(uniqueArrayValues(arr));
How to get distinct values from an array of objects in JavaScript?
If this were PHP I'd build an array with the keys and take array_keys
at the end, but JS has no such luxury. Instead, try this:
var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
if( flags[array[i].age]) continue;
flags[array[i].age] = true;
output.push(array[i].age);
}
Fastest way to get ONLY unique values from array?
The first idea, we can do over two step:
Step1: Sort the array
-- There are many algorithms to do it. As I know, currently, the complexity of best algorithm now is O(Nlog(N)) with N is the number of array.
Step2: Remove the duplicated elements
-- The complexity of this step is O(N)
So, over two steps, the complexity is O(N) + O(Nlog(N)). Finally, the complexity is O(Nlog(N))The second idea
This also has the complexity is O(Nlog(N)) but it will be O(N) for next time you want to get the unique age.
Instead of saving the data in array, you can rebuild in a binary search tree with a little custom. This node in this tree will save all the elements with same age.
The complexity for the first time you build the tree is O(Nlog(N))
About the algorithm which has the complexity is O(N), currently, I think there are no technique to solve it. :D
Related Topics
What Do These JavaScript Bitwise Operators Do
I Know That Callback Function Runs Asynchronously, But Why
Why Is My React Component Is Rendering Twice
Can (A== 1 && a ==2 && A==3) Ever Evaluate to True
What Does "This" Mean in Jquery
Angularjs "Controller As" Syntax - Clarification
Differencebetween String Primitives and String Objects in JavaScript
JavaScript Global Event Mechanism
Why Doesn't My Equality Comparison Using = (A Single Equals) Work Correctly
How to Render an Array of Objects in React
Why Does Firebase Lose Reference Outside the Once() Function
Function with Foreach Returns Undefined Even with Return Statement
Passing Custom Props to Router Component in React-Router V4
How to Check a Not-Defined Variable in JavaScript
How to Sort an Array on Multiple Columns
Number Prime Test in JavaScript