-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
  • 155,085
  • 27
  • 166
  • 222
Arsen
  • 7
  • 2
  • 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

3 Answers3

-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,287
  • 2
  • 6
  • 22
  • 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
  • 3,458
  • 1
  • 3
  • 18
-2
const uniqueValuesSet = new Set();
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"},
];

const filteredArray = arrPath.filter((obj) => {
  const isPresentInSet = uniqueValuesSet.has(obj.current);
  uniqueValuesSet.add(obj.current);
  return !isPresentInSet;
});

console.log(filteredArray);