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);
});
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]);
}
How can we delete a duplicated element in an array in C?
Here's my solution. No need to create a new array
#include <stdio.h>
int main()
{
int arr[6] = {1,2,3,3,8,5};
int temp,i,j, size = 6;
for(i = 0; i < size; i++){
for(j = i+1; j < size; j++){
if(arr[i] == arr[j]){
for(int k = j; k < size; k++){
arr[k] = arr[k+1];
}
size--;
j--;
}
}
}
for(int k = 0; k < size; k++){
printf("%d,", arr[k]);
}
return 0;
}
Thanks for all the help
how to remove first element of duplicate in an array of objects
This will give you an array with the last value for duplicated elements, in preserved order. If you want exactly the 2nd one you need an extra flag
array=[{id:34,value:45}, {id:23,value:35}, {id:34,value:28}]
const obj = array.reduce ( (acc,cur,index) => {
acc[cur.id] = {index:cur};
return acc;
},{});
const output = Object.values(obj).sort( (a,b) => a.index - b.index).map( ({index:val}) => val )
console.log(output)
remove all elements that occur more than once from array
In short: keep the value if the position of the first occurrence of the element (indexOf
) is also the last position of the element in the array (lastIndexOf
).
If the indexes are not equal then the value is duplicated and you can discard it.
const a = ['Ronaldo', 'Pele', 'Maradona', 'Messi',
'Pele', 'Messi', 'Jair', 'Baggio', 'Messi',
'Seedorf'];
const uniqueArray = a.filter(function(item) {
return a.lastIndexOf(item) == a.indexOf(item);
});
console.log(uniqueArray);
/* output: ["Ronaldo", "Maradona", "Jair", "Baggio", "Seedorf"] */
Codepen Demo
Related Topics
How to Find Out Who Is Connected to Actioncable
Ruby Block to String Instead of Executing
Linkedin API for Company Directory
Elasticsearch & Tire: Using Mapping and To_Indexed_JSON
Get All Instance Variables Declared in Class
How to Skip Has_Secure_Password Validations
Redirect User After Log in Only If It's on Root_Path
Reading and Updating Yaml File by Ruby Code
Force Browser to Download File Instead of Opening It
How to Copy File Across Buckets Using Aws-S3 or Aws-Sdk Gem in Ruby on Rails
Which Ruby Version am I Really Running
Difference Between Resource and Resources in Rails Routing
How to Calculate How Many Years Passed Since a Given Date in Ruby
Rack::Request - How to Get All Headers
How to Enable Tls V1.2 in Ruby? If So, How
Rails 3.1 Absolute Url to an Image
What Are <-- Ruby Strings Called? and How to Insert Variables in Them