0

I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}] I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance

let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']}, 
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
        
 let uniqueArray = arr.values.filter(function(item, pos) {
            return arr.values.indexOf(item.values) == pos;
   })

        console.log(uniqueArray)
 } 
}
Nightcrawler
  • 943
  • 1
  • 11
  • 32

1 Answers1

2

You can easily remove duplicates from an Array by creating a new Set based off it.

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection

If you want the result in an array, just use spread syntax for that, for example:

let arr = [{
    name: 'test1',
    values: ['35,5', '35,2', '35,2', '35,3', '35,5']
  },
  {
    name: 'test2',
    values: ['35,1', '35,1', '33,2', '34,3', '32,5']
  }
];

const uniqueArr = arr.reduce((accum, el) => {
  // Copy all the original object properties to a new object
  const obj = {
    ...el
  };

  // Remove the duplicates from values by creating a Set structure
  // and then spread that back into an empty array
  obj.values = [...new Set(obj.values)];

  accum.push(obj);

  return accum;
}, []);

uniqueArr.forEach(el => console.dir(el));
Tom O.
  • 5,730
  • 2
  • 21
  • 35