0

I have this array

array = [
         {id: "one", title: "new 1"},
         {id: "two", parent_id: "132132", title: "new 2"},
         {id: "three", parent_id: "132132", title: "new 3"},
         {id: "four", parent_id: "132132", title: "new 1"},
         {id: "one", parent_id: "132132", title: "new 1"}
        ]

We need

array = [
         {id: "two", parent_id: "132132", title: "new 2"},
         {id: "three", parent_id: "132132", title: "new 3"},
         {id: "four", parent_id: "132132", title: "new 1"},
         {id: "one", parent_id: "132132", title: "new 1"}
        ]

We need to compare elements to get unique array with different avoiding other elements

I have tried using this method

uniqueArray = (arr) => {
  return arr.filter((e, i, arr) => arr.findIndex(e2 => Object.keys(e2).every(prop => e2[prop] === e[prop])) === i);
};
5
  • As far as i can see all values are unique in this array, no duplicates. Be more specific based on what exactly do you want to filter this array. Commented Jul 10, 2019 at 7:05
  • You mean to say with unique id? What should be the behaviour for the duplicates? Which ones take precedence? The last one? Commented Jul 10, 2019 at 7:11
  • yes please. unique with id element Commented Jul 10, 2019 at 8:33
  • Also, need in return parent id 's hash Commented Jul 10, 2019 at 8:34
  • @ArpitVaishnav in the example array, the only one that is excluded does not have a parent_id. Is it safe to say that's the case for all duplicates? Commented Jul 10, 2019 at 8:56

2 Answers 2

1

I prefer Array.reduce for this kind of things:

const filteredArr = arr.reduce((acc, current) => {
  const exists = acc.find(item => item.id === current.id);
  if (!exists) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);
Sign up to request clarification or add additional context in comments.

Comments

0

If I understand you correctly, you want to return object without the property of parentId. If so you can use this.

array.filter(arr => arr.hasOwnProperty("parentId"))

2 Comments

thanks , how can we compare with id and keep parent id hash?
What you will get after this filter an array of objects with parentId properties. Do you want to also store the objects without the parentId somewhere else?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.