Remove duplicates in an object array Javascript
Plain javascript (ES2015), using Set
const list = [{ x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 1, y: 2 }];const uniq = new Set(list.map(e => JSON.stringify(e)));const res = Array.from(uniq).map(e => JSON.parse(e));document.write(JSON.stringify(res));
Try using the following:
list = list.filter((elem, index, self) => self.findIndex( (t) => {return (t.x === elem.x && t.y === elem.y)}) === index)
Vanilla JS version:
const list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}];function dedupe(arr) { return arr.reduce(function(p, c) { // create an identifying id from the object values var id = [c.x, c.y].join('|'); // if the id is not found in the temp array // add the object to the output array // and add the key to the temp array if (p.temp.indexOf(id) === -1) { p.out.push(c); p.temp.push(id); } return p; // return the deduped array }, { temp: [], out: [] }).out;}console.log(dedupe(list));