-1

I am trying to get rid of duplicates from withing a array but I am trying to get rid of the original of those duplicates as well just leaving anything that has not been repeated more than once

Example:

 const jsonarray = [{num: 1}, {num: 1}, {num: 2}, {num: 3}, {num: 5}, {num: 5}];

This is what I want the result to be

 [{num: 2}, {num: 3}];

I have tried splicing with nested for loop but that did not work any help would be appreciated.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Jack Syed
  • 3
  • 2
  • show what `I have tried` - personally, I'd use "filter" – Jaromanda X Sep 04 '19 at 01:15
  • 1
    If you have tried something, then you must show your work. What happens if someone else says `try X` and you reply `oh I already did try that`. Then you have just wasted their time for nothing. – JK. Sep 04 '19 at 01:15
  • Note that there's no such thing as a "JSON array". What you are showing there is an array of objects, no JSON involved. JSON is a text format for storing and sending data. – Heretic Monkey Sep 04 '19 at 01:17
  • The answer is to [Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array](https://stackoverflow.com/q/840781/215552) and create a separate array of that, then [Remove array of objects from another array of objects](https://stackoverflow.com/q/47017770/215552). – Heretic Monkey Sep 04 '19 at 01:31

2 Answers2

-1
var track = jsonarray.length;
for(var i = 0; i < track; i++) {
    var duplicate = false;
    for(var j = 0; j < jsonarray.length; j++) {
        if(i != j && jsonarray[i] == jsonarray[j]) {
            duplicate = true;
            jsonarray.splice(j, 1);
            if(j < i) {
                i--;
                track--;
            }
        }
    }
    if(duplicate) {
        jsonarray.splice(i, 1);
        i--;
        track--;
    }
}
user10433783
  • 103
  • 7
-1

const jsonarray = [{num: 1}, {num: 1}, {num: 2}, {num: 3}, {num: 5}, {num: 5}];

// filter out all the elements that have the same num but different indexes
const filtered = jsonarray.filter((a, indexA) => !jsonarray.find((b, indexB) => b.num === a.num && indexA !== indexB));

console.log(filtered);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60