-2

I have array objects with keys path and current. How to remove duplicate elements, where key current has the same value.

let arrPath = [{
  path: [1, 2],
  current: "K"
}, {
  path: [0, 3],
  current: "I"
}, {
  path: [1, 3],
  current: "N"
}, {
  path: [1, 4],
  current: "N"
}, {
  path: [0, 2],
  current: "G"
}, {
  path: [2, 2],
  current: "G"
} ];
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Arsen
  • 7
  • 1
  • 3
  • From dupe: `arrPath = arrPath.filter((item, index, self) => self.findIndex(t => t.current === item.current) === index)` – mplungjan Dec 26 '21 at 09:38
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Dec 26 '21 at 09:43

2 Answers2

-1

You can remove duplicate objects (duplicate object in the sense that it contains duplicate current property) by using reduce.

let arrPath = [{ path: [1, 2], current: "K" }, { path: [0, 3], current: "I" }, { path: [1, 3], current: "N" }, { path: [1, 4], current: "N" }, { path: [0, 2], current: "G" }, { path: [2, 2], current: "G" }]

let resultData = arrPath.reduce((elements, obj, index) => {
  let existingData = elements.find(element =>
    element.current === obj.current
  );
  if (!existingData) {
    elements.push(obj);
  }
  return elements;
}, []);

console.log(resultData)
Deepak
  • 2,660
  • 2
  • 8
  • 23
  • Reduce instead of filter?. Also a massive dupe. Here is a version from the dupe I chose to close the question with `arrPath = arrPath.filter((item, index, self) => self.findIndex(t => t.current === item.current) === index)` – mplungjan Dec 26 '21 at 09:39
  • A neater reduce also from the dupe: `Object.values(arrPath.reduce((acc,cur)=>Object.assign(acc,{[cur.current]:cur}),{}))` – mplungjan Dec 26 '21 at 09:48
-2

You can map each value in the array to an entry using the current values for the keys.

Then use these entries to construct a Map object, effectively eliminating duplicate entries.

You can convert the Map back to an array using Array.from

Array.from(new Map(arrPath.map(o => [o.current, o])).values())
skara9
  • 4,042
  • 1
  • 6
  • 21