0
 "name": [
        {
            "name": "test1"
        },
        {
            "name": "test2"
        },
        {
            "name": "test3"
        },
        {
            "name": "test1"
        },
]

I have the above created by nodejs. During array push, I would like to remove duplicated arrays from the list or only push the name array if the individual array does not exist.

I have tried below codes but it changes the array.

        var new = [];   
        for (var i =0;i<name.length;i++){
            new['name'] = name[i].name;
        }
Cristal
  • 492
  • 4
  • 21
  • Possible duplicate of [Remove duplicate values from JS array](https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array) – SanSolo Dec 07 '18 at 02:40
  • @SanSolo not looking for the solution given in that post. – Cristal Dec 07 '18 at 02:42
  • 1
    Could you please clarify what results you expect? And how multiple filtering methods from suggested link did not work for your case? In particular "would like to remove duplicated arrays from the list" - there are no "duplicated arrays" in the sample shown in the post (unless you interchangeably use "array" and "object" - note that this does not make question any more clear) – Alexei Levenkov Dec 07 '18 at 02:59
  • what do you mean by duplicated arrays? Could you please add a sample output in the question itself? – Harshith Rai Dec 07 '18 at 08:36

3 Answers3

1

The easiest way is probably with Array.prototype.reduce. Something along these lines, given your data structure:

obj.name = Object.values(obj.name.reduce((accumulator, current) => {
  if (!accumulator[current.name]) {
    accumulator[current.name] = current
  }
  return accumulator
}, {}));

The reduce creates an object that has keys off the item name, which makes sure that you only have unique names. Then I use Object.values() to turn it back into a regular array of objects like in your data sample.

Paul
  • 35,689
  • 11
  • 93
  • 122
0

the solution can be using temp Set;

const tmpSet = new Set();
someObj.name.filter((o)=>{
   const has = tmpSet.has(o.name);
   tmp.add(o.name);
   return has;
});

the filter function iterating over someObj.name field and filter it in place if you return "true". So you check if it exists in a tmp Set & add current value to Set to keep track of duplicates.

PS: new is a reserved word in js;

setdvd
  • 221
  • 1
  • 7
-1

This should do it

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

let unique = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'

https://wsvincent.com/javascript-remove-duplicates-array/

Epunx2
  • 1
  • 2