Each for object? [duplicate]

Asked
Active3 hr before
Viewed126 times

9 Answers

duplicateobject
90%

Array.filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ({id} destructs the object into only its id). To only filter out actual duplicates, it is using Array.includes()'s second parameter fromIndex with index + 1 which will ignore the current object and all previous.,Since every iteration of the filter callback method will only search the array beginning at the current index + 1, this also dramatically reduces the runtime because only objects not previously filtered get checked.,Some of the objects in your array may have additional properties that you are not interested in, or you simply want to find the unique objects considering only a subset of the properties.,This will remove duplicate objects and also preserve the types of the objects.

How about with some es6 magic?

things.thing = things.thing.filter((thing, index, self) =>
   index === self.findIndex((t) => (
      t.place === thing.place && t.name === thing.name
   ))
)

A more generic solution would be:

const uniqueArray = things.thing.filter((thing, index) => {
   const _thing = JSON.stringify(thing);
   return index === things.thing.findIndex(obj => {
      return JSON.stringify(obj) === _thing;
   });
});

Using the above property strategy instead of JSON.stringify:

const isPropValuesEqual = (subject, target, propNames) =>
   propNames.every(propName => subject[propName] === target[propName]);

const getUniqueItemsByProperties = (items, propNames) =>
   items.filter((item, index, array) =>
      index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))
   );

You can add a wrapper if you want the propNames property to be either an array or a value:

const getUniqueItemsByProperties = (items, propNames) => {
   const propNamesArray = Array.from(propNames);

   return items.filter((item, index, array) =>
      index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray))
   );
};
load more v
88%

new Set(addresses.map(a => a.id)) Set will only allow unique values in it, so i'm going to pass it the ids of each object. If the loop tries to add the same value again, it'll get ignored for free.,Here's another possibility using the Map class constructor and values method: ,I was getting from my async http call an array of objects (addresses in this case), but for unimportant reasons this array was returning objects that could be duplicate (so two identical ids).,Thanks for the code snippet, Marina...I'm getting to errors when I attempt to use it. The first is "Set is only referred to a type but is being used as a value here"

const addresses = [...]; // Some array I got from async call

const uniqueAddresses = Array.from(new Set(addresses.map(a => a.id)))
   .map(id => {
      return addresses.find(a => a.id === id)
   })
load more v
72%

Given an array of objects and the task is to remove the duplicate object element from the array list. There are two methods to solve this problem which are discussed below:,PHP | Different characters in the given string,Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.,How to get all unique values (remove duplicates) in a JavaScript array?

65%

Also, if the value of the property in the object is Date, then using JSON.stringify will convert the Date object to a string.,Circular objects are objects that have a property value referencing to themselves.,In JavaScript, a variable can store two types of data:,Articles related to JavaScript.

When we copy primitive values, only the value will be copied.

var a = 10;
var b = a;
console.log(a, b); // 10, 10b = 20;console.log(a, b); // 10, 20

But when we copy reference values, the memory address of the object is shared.

var a = {
   one: 1
};
var b = a;
a.one = 2;
console.log(b.one); // 2b.one = 3;console.log(a.one); //3
load more v
75%

However, that approach doesn’t work with the following data because a Set would consider each object to be unique:,We use a Set to record unique keys of members that we have visited.,We only add an object from members to uniqueMembers1 if it doesn’t already exist in that Array. That’s why the earlier Jane with ID '10yejma' “wins”.,This may help with large Arrays because we don’t have to search them. On the other hand, creating keys and maintaining a Set affects performance negatively.

Eliminating duplicate values from Arrays is simple – as long as the values are primitive (and therefore compared by value):

const values = ['jane', 'lars', 'jane'];
const uniqueValues = [...new Set(values)];
assert.deepEqual(
   uniqueValues,
   ['jane', 'lars']);
load more v
40%

Now we have two variables, each storing a reference to the same object:,So, copying an object variable creates one more reference to the same object.,As a result we have two independent variables, each one storing the string "Hello!".,As you can see, there’s still one object, but now with two variables that reference it.

let message = "Hello!";
let phrase = message;
load more v
22%

To remove these duplicate object elements first let's create a Set object to hold unique values. It can be done like this,,Now let' use the array filter() method to loop over each array elements (in our case objects are the elements) and filter out some elements based on certain condition. It can be done like this,,Now inside the filter() method, we can write the logic to filter out the array elements.,Let's say i have an array with some objects as elements, the objects has property called name where some of the values are repeated more than once like this,

TL;DR

// initialize a Set object
const uniqueValuesSet = new Set();

// array of objects with duplicate values
const arr = [{
      name: "John Doe"
   },
   {
      name: "John Doe"
   },
   {
      name: "Lily Roy"
   },
   {
      name: "Helen"
   },
];

const filteredArr = arr.filter((obj) => {
   // check if name property value is already in the set
   const isPresentInSet = uniqueValuesSet.has(obj.name);

   // add name property value to Set
   uniqueValuesSet.add(obj.name);

   // return the negated value of
   // isPresentInSet variable
   return !isPresentInSet;
});
load more v
60%

The best way to remove duplicates from an array of objects in JavaScript?,Removing duplicates from a sorted array of literals in JavaScript,Remove duplicates from array with URL values in JavaScript,Remove duplicates and map an array in JavaScript

Example

const arr = [{
      "timestamp": 564328370007,
      "message": "It will rain today"
   },
   {
      "timestamp": 164328302520,
      "message": "will it rain today"
   },
   {
      "timestamp": 564328370007,
      "message": "It will rain today"
   },
   {
      "timestamp": 564328370007,
      "message": "It will rain today"
   }
];
const map = {};
const newArray = [];
arr.forEach(el => {
   if (!map[JSON.stringify(el)]) {
      map[JSON.stringify(el)] = true;
      newArray.push(el);
   }
});
console.log(newArray);
load more v
48%

var yourArray = [

   {
      Index: 1,
      Name: "Farley, Charley",
      EmployeeCode: "12",
      PaymentType: "Void",
      CheckDate: "01/04/2012"
   },
   {
      Index: 2,
      Name: "Farley, Charley",
      EmployeeCode: "12",
      PaymentType: "Void",
      CheckDate: "01/04/2012"
   },
   {
      Index: 3,
      Name: "Tarley, Charley",
      EmployeeCode: "12",
      PaymentType: "Void",
      CheckDate: "01/04/2012"
   }
];

unique = [...new Set(yourArray.map(propYoureChecking => propYoureChecking.Name))];
if (unique.length === 1) {
   console.log(unique);
}
load more v

Other "duplicate-object" queries related to "Each for object? [duplicate]"