How to Check If the Array of Objects Have Duplicate Property Values

How can I check if the array of objects have duplicate property values?

Use array.prototype.map and array.prototype.some:

var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName2' }
];

var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){
return valueArr.indexOf(item) != idx
});
console.log(isDuplicate);

Get list of duplicate objects in an array of objects

You can use Array#reduce to make a counter lookup table based on the id key, then use Array#filter to remove any items that appeared only once in the lookup table. Time complexity is O(n).

const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
const lookup = values.reduce((a, e) => { a[e.id] = ++a[e.id] || 0; return a;}, {});
console.log(values.filter(e => lookup[e.id]));

Checking for duplicate property values in an array of nested objects

There were quite a few errors in your code, I have fixed them. What seemed to confuse you the most was that you had an array of a single item, that is an object, which has an items member that's an array as well. So, we needed to refer data[0].items[x] instead of data[x]. Also, in your checkIfPresent function you checked whether data contains the item, which is obviously true. Always. Instead, you wanted to check whether an item of the same name was already processed, so you needed to check whether arr already had this value. Finally, arr is initialized in every iteration of your loop, which removes anything that was stored in an earlier iteration and makes it unaccessible outside the loop. I moved the initialization outside the loop. Also, since your data has an array, it seems that you may have several shoppings. In which case you can wrap another loop around the loop that you already have and loop data's main index as well.

let data = [
{
"email": "tshepo@email.com",
"status": "OPEN",
"items": [
{
"name": "hamster",
"quantity": 2,
"price": 20
},
{
"name": "saw dust",
"quantity": 1,
"price": 20
},
{
"name": "hamster-cage",
"quantity": 1,
"price": 150
},
{
"name": "book: how to care for your hamster",
"quantity": 1,
"price": 150
},
{
"name": "hamster-cage",
"quantity": 1,
"price": 150
}
]
}
]
function checkIfPresent(key, array){
let ans = array.findIndex((obj) => obj.name === key)
return ans;
}

let arr = [];var ans;
for(let x = 0; x < data[0].items.length; x++)
{
if((ans = checkIfPresent(data[0].items[x].name, arr)) >= 0){
arr[ans].quantity += data[0].items[x].quantity;
}else{
arr.push(data[0].items[x]);
}
}
console.log(arr);

How can I check if the array of objects have duplicate property values with more properties?

You can use .map() to map each object to a string. Each string takes the shape of type-id for that object. Then, using a Set you can remove all duplicate strings. You can then check if the set size equals the array length to determine if there are any duplicates or not in the array:

const containsDups = arr => new Set(arr.map(({type, id}) => `${type}-${id}`)).size !== arr.length;
const arr = [{type: 1, id: 1, name:'aa'},{type: 1, id: 1, name:'bb'},{type: 2, id: 1, name:'cc'}];console.log(containsDups(arr));

find duplicate values in array of objects in javascript

Assuming both id and dt properties are significant, I would first create a means of hashing an entry and then build a hashed set of required_documents.

Then you can filter out anything from existing_documents that is in the set, leaving only the results you want.

const required_documents = [{"id":1,"dt":1},{"id":2,"dt":2},{"id":3,"dt":3}];
const existing_documents = [{"id":1,"dt":1},{"id":2,"dt":2},{"id":3,"dt":4}];

// a simple stringify hash
const createHash = ({ id, dt }) => JSON.stringify({ id, dt });

const requiredHashSet = new Set(required_documents.map(createHash));

const result = existing_documents.filter(
(doc) => !requiredHashSet.has(createHash(doc))
);

console.log(result);

Find duplicate object based on value property in array of objects and then reduce the array concatenating the duplicate object in its label property

This could be achieved with a for loop. Loop over the objects, construct a new array, check if value already exists and if it does concatenate the label, otherwise add a new entry:

function removeDuplicates(arr) {
const newArr = [];

for (const obj of arr) {
const existing = newArr.find((el) => el.value === obj.value);
if (existing) {
existing.label += "/" + obj.label;
} else {
newArr.push(obj);
}
}

return newArr;
}

console.log(removeDuplicates([
{value: "2021", label: "REDS"},
{value: "2020", label: "REDS"},
{value: "2021", label: "COPASA"},
{value: "2021", label: "CEMIG_CLIENTES"},
{value: "2016", label: "CEMIG_CLIENTES"},
{value: "2016", label: "RFQSA"}
]));

How to find duplicate values in a JavaScript array of objects, and output only unique values?

You could use a Set in combination with Array#map and a spread operator ... in a single line.

Map returns an array with all names, which are going into the set initializer and then all values of the set are returned in an array.

var family = [{ name: "Mike", age: 10 }, { name: "Matt", age: 13 }, { name: "Nancy", age: 15 }, { name: "Adam", age: 22 }, { name: "Jenny", age: 85 }, { name: "Nancy", age: 2 }, { name: "Carl", age: 40 }],    unique = [...new Set(family.map(a => a.name))];
console.log(unique);

Find duplicate objects in array and return new array of object with number of duplicates as a new property

I think you'd be best suited by creating a helper object. A helper object will initially be empty, but will become populated slowly by what you're reading through. I'm going to assume that the keys in your array are consistent.

const keys = ["Name","Type"]
var counterObj = {}
let keyForCounterObj
arrayOfObjects.forEach((obj)=>{
keyForCounterObj = ''
keys.forEach((key)=>{
keyForCounterObj += String(obj[key])
}
if(counterObj[keyForCounterObj]){
counterObj[keyForCounterObj].times ++
}else{
counterObj[keyForCounterObj] = {
...obj,
times:1
}}}

Let's break that down, because I understand that it might be a little bit confusing if you've never seen this setup before.

We're looping through each object in the array, and we're constructing a key based on all of the values that this object is storing. For example, arrayOfObjects[0] will create a key of "AppleFruit." (I'm using the String() method just in case this is being applied to an object with only integer or floating point values, as those are invalid to create a key in javaScript. It isn't necessary for your specific question)

Once we have that key, we check to see if it exists in our counterObject. If it does not exist, then we define it. We set the "times" attribute to 1, because we just created this object; it wouldn't exist unless we had just found it.

If the object does already exist, then we just increment the "times" attribute. At the end, we have an object that looks like this:

counterObj = {
AppleFruit: {
Name:"Apple",
Type:"Fruit",
times:3,
},
CarrotVegetable:{
Name:"Carrot",
Type:"Vegetable",
times:4,
}
}

Okay, so now we have an object of objects. Let's turn that into an array!

let newArrayOfObjects = []
const counterObjKeys = Object.keys(counterObj)
counterObjKeys.forEach((key)=>{
newArrayOfObjects.push(counterObj[key])
}

This will return the final value in the format that you specified!



Related Topics



Leave a reply



Submit