Usuwanie duplikatów z tablicy obiektów w JavaScript

Mam obiekt, który zawiera tablicę obiektów.

things = new Object();

things.thing = new Array();

things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

Zastanawiam się, jaka jest najlepsza metoda usuwania duplikatów obiektów z tablicy. Na przykład rzeczy.coś by się stało...

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
Author: Donald Duck, 2010-02-08

30 answers

Zobaczmy ... prymitywny byłby:

var obj = {};

for ( var i=0, len=things.thing.length; i < len; i++ )
    obj[things.thing[i]['place']] = things.thing[i];

things.thing = new Array();
for ( var key in obj )
    things.thing.push(obj[key]);
Ok, myślę, że to powinno załatwić sprawę. Zobacz, Travis.

EDIT
Edytował kod, aby poprawnie odwoływać się do Właściwości place (poprzednia id).

 109
Author: aefxx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-30 22:02:52

Może trochę magii?

things.thing = things.thing.filter((thing, index, self) =>
  index === self.findIndex((t) => (
    t.place === thing.place && t.name === thing.name
  ))
)

Odnośnik URL

Dla front-endów może to być trochę za wcześnie, aby zaimplementować, ponieważ wiele używanych przeglądarek nadal nie obsługuje funkcji es6

 206
Author: Eydrian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 16:59:01

Jeśli możesz używać bibliotek Javascript, takich jak underscore lub lodash, polecam zajrzeć do _.uniq function w ich bibliotekach. From lodash:

_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])

Zasadniczo przekazujesz tablicę, która tutaj jest literalnym obiektem, a następnie przekazujesz atrybut, z którym chcesz usunąć duplikaty w oryginalnej tablicy danych, tak:

var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];
var non_duplidated_data = _.uniq(data, 'name'); 

Aktualizacja : Lodash wprowadził również .uniqBy.

 68
Author: ambodi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-09 17:00:05

Miałem dokładnie ten sam wymóg, aby usunąć duplikaty obiektów w tablicy, na podstawie duplikatów na jednym polu. Znalazłem kod tutaj: Javascript: Usuń duplikaty z tablicy obiektów

Więc w moim przykładzie usuwam dowolny obiekt z tablicy, który ma duplikat wartości ciągu licenseNum.

var arrayWithDuplicates = [
    {"type":"LICENSE", "licenseNum": "12345", state:"NV"},
    {"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"OR"},
    {"type":"LICENSE", "licenseNum": "10849", state:"CA"},
    {"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }

var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
console.log("uniqueArray is: " + JSON.stringify(uniqueArray));

Wyniki:

UniqueArray to:

[{"type":"LICENSE","licenseNum":"10849","state":"CA"},
{"type":"LICENSE","licenseNum":"12345","state":"NM"},
{"type":"LICENSE","licenseNum":"A7846","state":"CA"},
{"type":"LICENSE","licenseNum":"B7037","state":"WA"}]
 44
Author: James Drinkard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 12:45:34

Jeśli można poczekać z wyeliminowaniem duplikatów aż po dodaniu wszystkich, typowym podejściem jest najpierw posortowanie tablicy, a następnie wyeliminowanie duplikatów. Sortowanie pozwala uniknąć podejścia N * N skanowania tablicy dla każdego elementu podczas przechodzenia przez nie.

Funkcja "eliminuj duplikaty" jest zwykle nazywana unique lub uniq. Niektóre implementacje mogą łączyć te dwa kroki, np. prototype ' s uniq

Ten post ma kilka pomysły, aby spróbować (a niektóre, aby uniknąć :-) ) Jeśli biblioteka nie ma jeszcze! Osobiście uważam ten za najbardziej prosty:

    function unique(a){
        a.sort();
        for(var i = 1; i < a.length; ){
            if(a[i-1] == a[i]){
                a.splice(i, 1);
            } else {
                i++;
            }
        }
        return a;
    }  

    // Provide your own comparison
    function unique(a, compareFunc){
        a.sort( compareFunc );
        for(var i = 1; i < a.length; ){
            if( compareFunc(a[i-1], a[i]) === 0){
                a.splice(i, 1);
            } else {
                i++;
            }
        }
        return a;
    }
 21
Author: maccullt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-03 09:29:05

Oto inna opcja, aby zrobić to przy użyciu metod iteracji tablicy, jeśli potrzebujesz porównania tylko przez jedno pole obiektu:

    function uniq(a, param){
        return a.filter(function(item, pos, array){
            return array.map(function(mapItem){ return mapItem[param]; }).indexOf(item[param]) === pos;
        })
    }

    uniq(things.thing, 'place');
 17
Author: Alex Kobylinski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-26 14:06:47

Jedna wkładka za pomocą zestawu

var things = new Object();

things.thing = new Array();

things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

// assign things.thing to myData for brevity
var myData = things.thing;

things.thing = Array.from(new Set(myData.map(JSON.stringify))).map(JSON.parse);

console.log(things.thing)

Wyjaśnienie:

  1. new Set(myData.map(JSON.stringify)) tworzy obiekt Set przy użyciu stringified myData elements.
  2. Set obiekt zapewni, że każdy element jest unikalny.
  3. następnie tworzę tablicę opartą na elementach utworzonego zbioru za pomocą Array.od.
  4. wreszcie, używam JSON.parse do konwersji stringified elementu z powrotem do obiektu.
 16
Author: Mμ.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-17 06:30:16

Aktualizacja

Przeczytałem pytanie poprawnie. Jest to ogólny sposób na to: przechodzisz w funkcji, która sprawdza, czy dwa elementy tablicy są uważane za równe. W tym przypadku porównuje wartości właściwości name i place dwóch porównywanych obiektów.
function arrayContains(arr, val, equals) {
    var i = arr.length;
    while (i--) {
        if ( equals(arr[i], val) ) {
            return true;
        }
    }
    return false;
}

function removeDuplicates(arr, equals) {
    var originalArr = arr.slice(0);
    var i, len, j, val;
    arr.length = 0;

    for (i = 0, len = originalArr.length; i < len; ++i) {
        val = originalArr[i];
        if (!arrayContains(arr, val, equals)) {
            arr.push(val);
        }
    }
}

function thingsEqual(thing1, thing2) {
    return thing1.place === thing2.place
        && thing1.name === thing2.name;
}

removeDuplicates(things.thing, thingsEqual);
 14
Author: Tim Down,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-08 09:24:37

Inną opcją byłoby utworzenie niestandardowej funkcji indexOf, która porównuje wartości wybranej właściwości dla każdego obiektu i zawija ją w funkcję reduce.

var uniq = redundant_array.reduce(function(a,b){
      function indexOfProperty (a, b){
          for (var i=0;i<a.length;i++){
              if(a[i].property == b.property){
                   return i;
               }
          }
         return -1;
      }

      if (indexOfProperty(a,b) < 0 ) a.push(b);
        return a;
    },[]);
 7
Author: ZeroSum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-02 20:52:31

Możesz też użyć Map:

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

Pełna próbka:

const things = new Object();

things.thing = new Array();

things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

console.log(JSON.stringify(dedupThings, null, 4));

Wynik:

[
    {
        "place": "here",
        "name": "stuff"
    },
    {
        "place": "there",
        "name": "morestuff"
    }
]
 6
Author: Pragmateek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-26 00:05:50

Rozważając lodash.uniqWith

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
 6
Author: Justin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-20 04:30:28

Cholera, dzieci, rozwalmy to.

let uniqIds = {}, source = [{id:'a'},{id:'b'},{id:'c'},{id:'b'},{id:'a'},{id:'d'}];
let filtered = source.filter(obj => !uniqIds[obj.id] && (uniqIds[obj.id] = true));
console.log(filtered);
// EXPECTED: [{id:'a'},{id:'b'},{id:'c'},{id:'d'}];
 6
Author: Cliff Hall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-14 22:44:53

Jeden liner jest tutaj

let arr = [
  {id:1,name:"sravan"},
  {id:2,name:"anu"},
  {id:4,name:"mammu"},
  {id:3,name:"sanju"},
  {id:3,name:"ram"},
];

console.log(Object.values(arr.reduce((acc,cur)=>Object.assign(acc,{[cur.id]:cur}),{})))
 6
Author: sravan kumar ganji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-16 13:35:20

Aby dodać jeszcze jedną do listy. Używając ES6 i Array.reduce z Array.find.
W tym przykładzie filtrowanie obiektów na podstawie właściwości guid.

let filtered = array.reduce((accumulator, current) => {
  if (! accumulator.find(({guid}) => guid === current.guid)) {
    accumulator.push(current);
  }
  return accumulator;
}, []);
 4
Author: Pete B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-14 09:42:13

Oto rozwiązanie dla es6, w którym chcesz zachować tylko ostatnią pozycję. To rozwiązanie jest funkcjonalne i zgodne z Airbnb style.

const things = {
  thing: [
    { place: 'here', name: 'stuff' },
    { place: 'there', name: 'morestuff1' },
    { place: 'there', name: 'morestuff2' }, 
  ],
};

const removeDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]
 3
Author: Micah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-24 04:25:16

Jeśli nie masz nic przeciwko temu, że Twoja unikalna tablica zostanie posortowana później, będzie to skuteczne rozwiązanie:

things.thing
  .sort(((a, b) => a.place < b.place)
  .filter((current, index, array) =>
    index === 0 || current.place !== array[index - 1].place)

W ten sposób wystarczy porównać bieżący element z poprzednim elementem w tablicy. Sortowanie raz przed filtrowaniem (O(n*log(n))) jest tańsze niż szukanie duplikatu w całej tablicy dla każdego elementu tablicy (O(n²)).

 2
Author: Clemens Helm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-06 09:48:18

Słyszałeś o Bibliotece Lodash? Polecam ci to narzędzie, gdy naprawdę nie chcesz zastosować swojej logiki do kodu i użyć już obecnego kodu, który jest zoptymalizowany i niezawodny.

Rozważ utworzenie takiej tablicy

things.thing.push({place:"utopia",name:"unicorn"});
things.thing.push({place:"jade_palace",name:"po"});
things.thing.push({place:"jade_palace",name:"tigress"});
things.thing.push({place:"utopia",name:"flying_reindeer"});
things.thing.push({place:"panda_village",name:"po"});

Zauważ, że jeśli chcesz zachować jeden atrybut unikalny, możesz to zrobić używając biblioteki lodash. Tutaj możesz użyć _.uniqBy

.uniqBy(array, [iteratee=.tożsamość])

Ta metoda jest jak _.uniq (który zwraca pozbawioną duplikatów wersję tablicy, w której przechowywane jest tylko pierwsze wystąpienie każdego elementu), z wyjątkiem tego, że akceptuje iterację, która jest wywoływana dla każdego elementu w tablicy w celu wygenerowania kryterium, według którego obliczana jest unikalność.

Więc, na przykład, jeśli chcesz zwrócić tablicę posiadającą unikalny atrybut 'place'

_.uniqBy(słow.thing, 'place')

Podobnie, jeśli chcesz mieć unikalny atrybut jako 'nazwa'

_.uniqBy(słow.thing, 'name')

Mam nadzieję, że to pomoże. Zdrówko!
 2
Author: Mayank Gangwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-23 03:51:03

Jeśli nie chcesz podawać listy właściwości:

function removeDuplicates(myArr) {
  var props = Object.keys(myArr[0])
  return myArr.filter((item, index, self) =>
    index === self.findIndex((t) => (
      props.every(prop => {
        return t[prop] === item[prop]
      })
    ))
  )
}
OBS! Nie jest kompatybilny z IE11.
 2
Author: stoatoffear,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-20 09:36:16

Innym sposobem byłoby użycie funkcji reduce i posiadanie nowej tablicy jako akumulatora. Jeśli w tablicy akumulatorów znajduje się już thing o tej samej nazwie, nie dodawaj jej tam.

let list = things.thing;
list = list.reduce((accumulator, thing) => {
    if (!accumulator.filter((duplicate) => thing.name === duplicate.name)[0]) {
        accumulator.push(thing);
    }
    return accumulator;
}, []);
thing.things = list;

Dodaję tę odpowiedź, ponieważ nie mogłem znaleźć ładnego, czytelnego rozwiązania es6 (używam babel do obsługi funkcji strzałek), które jest kompatybilne z Internet Explorerem 11. Problem w tym, że IE11 nie ma Map.values() ani Set.values() bez polyfill. Z tego samego powodu użyłem filter()[0] Aby uzyskać pierwszy element zamiast z dnia find().

 1
Author: Keammoort,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-29 16:05:27
 var testArray= ['a','b','c','d','e','b','c','d'];

 function removeDuplicatesFromArray(arr){

 var obj={};
 var uniqueArr=[];
 for(var i=0;i<arr.length;i++){ 
    if(!obj.hasOwnProperty(arr[i])){
        obj[arr[i]] = arr[i];
        uniqueArr.push(arr[i]);
    }
 }

return uniqueArr;

}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);

Output:- [ 'a', 'b', 'c', 'd', 'e' ]
 1
Author: shubham verma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-21 07:51:03

RemoveDuplicates() pobiera tablicę obiektów i zwraca nową tablicę bez duplikatów obiektów (na podstawie właściwości id).

const allTests = [
  {name: 'Test1', id: '1'}, 
  {name: 'Test3', id: '3'},
  {name: 'Test2', id: '2'},
  {name: 'Test2', id: '2'},
  {name: 'Test3', id: '3'}
];

function removeDuplicates(array) {
  let uniq = {};
  return array.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true))
}

removeDuplicates(allTests);

Oczekiwany wynik:

[
  {name: 'Test1', id: '1'}, 
  {name: 'Test3', id: '3'},
  {name: 'Test2', id: '2'}
];

Najpierw ustawiamy wartość zmiennej uniq na pusty obiekt.

Następnie filtrujemy przez tablicę obiektów. Filter tworzy nową tablicę ze wszystkimi elementami, które przechodzą test zaimplementowany przez dostarczoną funkcję.

return array.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true));

Powyżej używamy funkcji zwarcia&&. Jeśli lewa strona z & & ocenia na true, wtedy zwraca wartość po prawej stronie&&. Jeśli lewa strona jest false, zwraca to, co znajduje się po lewej stronie&&.

Dla każdego obiektu (obj) sprawdzamy Uniq pod kątem właściwości o nazwie obj.id (w tym przypadku, na pierwszej iteracji będzie sprawdzać Właściwość '1'.) Chcemy odwrotności tego, co zwraca (albo prawda, albo fałsz), dlatego używamy! in! uniq[obj.id]. jeśli uniq ma już właściwość id, zwraca true, która zwraca wartość false (!) nakazując funkcji filtra nie dodawać tego obj. Jeśli jednak nie znajdzie obj.id właściwość, zwraca false, które następnie ocenia na true (!) i zwraca wszystko po prawej stronie&&, lub (uniq[obj.id] = true, Jest to wartość true, mówiąca metodzie filter, aby dodała OBJ do zwracanej tablicy, a także dodaje Właściwość {1: true} do uniq. Zapewnia to, że żadna inna instancja obj o tym samym id nie zostanie dodana ponownie.

 1
Author: MarkN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-29 22:20:53

Kontynuacja badania sposobów usuwania duplikatów z tablicy obiektów przez ES6: ustawianie thisArg argumentu Array.prototype.filter to new Set zapewnia przyzwoitą alternatywę:

const things = [
  {place:"here",name:"stuff"},
  {place:"there",name:"morestuff"},
  {place:"there",name:"morestuff"}
];

const filtered = things.filter(function({place, name}) {

  const key =`${place}${name}`;

  return !this.has(key) && this.add(key);

}, new Set);

console.log(filtered);

Nie będzie jednak działać z funkcjami strzałek () =>, ponieważ {[5] } jest związana z ich zakresem leksykalnym.

 1
Author: Leonid Pyrlia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-06 10:30:34

var uniq = {}
var arr  = [{"id":"1"},{"id":"1"},{"id":"2"}]
var arrFiltered = arr.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true));
console.log('arrFiltered', arrFiltered)
 1
Author: аlex dykyі,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-11 10:32:18
var data = [{
    'name': 'Amir',
    'surname': 'Rahnama'
}, {
    'name': 'Amir',
    'surname': 'Stevens'
}];
var non_duplidated_data = _.uniqBy(data, 'name');
 1
Author: qzttt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 06:52:18

Oto kolejna technika, aby znaleźć liczbę duplikatów i łatwo usunąć je z obiektu danych. "dupsCount" to liczba duplikatów plików. najpierw posortuj dane, a następnie usuń. to daje najszybsze usuwanie duplikacji.

  dataArray.sort(function (a, b) {
            var textA = a.name.toUpperCase();
            var textB = b.name.toUpperCase();
            return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
        });
        for (var i = 0; i < dataArray.length - 1; ) {
            if (dataArray[i].name == dataArray[i + 1].name) {
                dupsCount++;
                dataArray.splice(i, 1);
            } else {
                i++;
            }
        }
 0
Author: HD..,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-24 12:09:58

Oto rozwiązanie wykorzystujące nową funkcję filtrowania JavaScript, które jest dość proste . Powiedzmy, że masz taką tablicę.

var duplicatesArray = ['AKASH','AKASH','NAVIN','HARISH','NAVIN','HARISH','AKASH','MANJULIKA','AKASH','TAPASWENI','MANJULIKA','HARISH','TAPASWENI','AKASH','MANISH','HARISH','TAPASWENI','MANJULIKA','MANISH'];

Funkcja filter pozwoli Ci utworzyć nową tablicę, używając funkcji wywołania zwrotnego raz dla każdego elementu w tablicy. Więc możesz ustawić unikalną tablicę w ten sposób.

var uniqueArray = duplicatesArray.filter(function(elem, pos) {return duplicatesArray.indexOf(elem) == pos;});

W tym scenariuszu unikalna tablica będzie przebiegać przez wszystkie wartości w zduplikowanej tablicy. Zmienna elem przedstawia wartość elementu w array (mike, james, james, alex), pozycja jest 0-indeksowana w tablicy (0,1,2,3...), a także powielacze.wartość indexOf (elem) jest tylko indeksem pierwszego wystąpienia tego elementu w oryginalnej tablicy. Tak więc, ponieważ element 'james' jest duplikowany, kiedy przechodzimy przez wszystkie elementy w duplicatesArray i pchamy je do uniqueArray, za pierwszym razem trafiamy Jamesa, nasza wartość " pos " wynosi 1, a nasz indexOf(elem) również wynosi 1, więc James zostaje zepchnięty do uniqueArray. Za drugim razem, gdy uderzymy Jamesa, nasza wartość" pos " wynosi 2, a nasz indexOf(elem) nadal wynosi 1 (ponieważ znajduje tylko pierwszą instancję elementu tablicy), więc duplikat nie jest wypychany. Dlatego nasza unikalnośćearray zawiera tylko unikalne wartości.

Oto Demo powyższej funkcji.Kliknij tutaj, aby zobaczyć powyższy przykład funkcji

 0
Author: HARISH TIWARY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-10 10:06:32

Jeśli potrzebujesz unikalnej tablicy opartej na wielu właściwościach obiektu, możesz to zrobić za pomocą map i łącząc właściwości obiektu.

    var hash = array.map(function(element){
        var string = ''
        for (var key in element){
            string += element[key]
        }
        return string
    })
    array = array.filter(function(element, index){
        var string = ''
        for (var key in element){
            string += element[key]
        }
        return hash.indexOf(string) == index
    })
 0
Author: ykay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-22 11:37:03

Ogólne dla dowolnej tablicy obiektów:

/**
* Remove duplicated values without losing information
*/
const removeValues = (items, key) => {
  let tmp = {};

  items.forEach(item => {
    tmp[item[key]] = (!tmp[item[key]]) ? item : Object.assign(tmp[item[key]], item);
  });
  items = [];
  Object.keys(tmp).forEach(key => items.push(tmp[key]));

  return items;
}
Mam nadzieję, że to może pomóc komukolwiek.
 0
Author: aSoler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-05 16:52:12

Jest to prosty sposób na usunięcie dwulicowości z tablicy obiektów.

Dużo pracuję z danymi i jest to dla mnie przydatne.

const data = [{name: 'AAA'}, {name: 'AAA'}, {name: 'BBB'}, {name: 'AAA'}];
function removeDuplicity(datas){
    return datas.filter((item, index,arr)=>{
    const c = arr.map(item=> item.name);
    return  index === c.indexOf(item.name)
  })
}

console.log(removeDuplicity(data))

Wyświetli w konsoli:

[[object Object] {
name: "AAA"
}, [object Object] {
name: "BBB"
}]
 0
Author: Juraj Sarissky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-09 02:23:19
str =[
{"item_id":1},
{"item_id":2},
{"item_id":2}
]

obj =[]
for (x in str){
    if(check(str[x].item_id)){
        obj.push(str[x])
    }   
}
function check(id){
    flag=0
    for (y in obj){
        if(obj[y].item_id === id){
            flag =1
        }
    }
    if(flag ==0) return true
    else return false

}
console.log(obj)

Str jest tablicą obiektów. Istnieją obiekty o tej samej wartości (tutaj mały przykład, są dwa obiekty o tym samym identyfikatorze item_id co 2). check (id) jest funkcją, która sprawdza, czy jakiś obiekt o tym samym identyfikatorze item_id istnieje czy nie. jeśli istnieje, zwróć false, w przeciwnym razie zwróć true. Zgodnie z tym wynikiem, wepchnij obiekt do nowej tablicy obj Wynikiem powyższego kodu jest [{"item_id":1},{"item_id":2}]

 0
Author: Bibin Jaimon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-06 03:05:43