Remove from the Array Elements That Are Repeated

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



Leave a reply



Submit