Delete Documents that have the same of certain field [duplicate] - javascript

This question already has answers here:
MongoDB Duplicate Documents even after adding unique key
(4 answers)
mongodb get distinct records
(6 answers)
Closed 3 years ago.
I have a data in MongoDB and I want to remove all the duplicated Documents. The problem is MongoDB assigns each item a unique _id so I can't just delete the duplicated items. I have a field in each Document called name and I want to delete the items that have the same name.
For example:
[{_id: 5c7e423f0bdaa9aeb5399e90,
name ="A"
grade = 16
enrolled ="dddh"
},
{_id: 5c7e423f1bdaa9aeb5399e90,
key ="B"
grade =17
note ="ddddd"
},
{_id: 5c7e423d0bdaa9aeb5399e90,
key ="B"
score =17
note ="ddddd"
}]
to:
[{_id: 5c7e423f0bdaa9aeb5399e90,
name ="A"
grade = 16
enrolled ="dddh"
},
{_id: 5c7e423f1bdaa9aeb5399e90,
name ="B"
grade =17
enrolled ="ddddd"
}]
The list might be big so is there any efficient way to do it?

First note your structure contains a lot of syntax errors. Now, one solution is to use Array.reduce() over your original array of objects to generate a new object using the name properties as the keys of this new object. This will ensure you will end up with only one object associated per name property. Finally, you can use Object.values() to get your desired output.
let input = [
{
_id: "5c7e423f0bdaa9aeb5399e90",
name: "A",
grade: 16,
enrolled: "dddh"
},
{
_id: "5c7e423f1bdaa9aeb5399e90",
name: "B",
grade: 17,
note: "ddddd"
},
{
_id: "5c7e423d0bdaa9aeb5399e90",
name: "B",
score: 17,
note: "ddddd"
}
];
let res = input.reduce((acc, curr) =>
{
acc[curr.name] = acc[curr.name] || curr;
return acc;
}, {});
console.log(Object.values(res));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Related

How to determine if my array of object has an attribute with a specific value

I have an array of object like so
[{name: "Apple", price: "10", quantity: "1"},{name: "Dog", price: "55", quantity: "2"},{name: "Car", price: "88", quantity: "4"},]
etc
How do I determine if for example my 2. object's name == Dog?
My IRL Example is this: I have a shopping cart and I don't want to add the same product twice
const handleAddToCart = (product)=>{
console.log(inCart)
if(!inCart.includes(product)){
product.quantity = product.quantity+1;
setInCart(inCart.concat(product));
}
}
InCart is my array of object and product is 1 object from the array
The above version is not good because I update the quantity property and after I reset the page it will add multiply times
You can use Array#some to check if there is already an object with a specific name.
let name = "Dog";
let hasDuplicate = inCart.some(x => x.name === name);
For increased performance, consider storing a Set of names for constant-time lookup.

How do I sort in the front end with javascript an array of items based on other fields inside the item [duplicate]

This question already has answers here:
How to sort an array of objects by multiple fields?
(38 answers)
Closed 2 years ago.
I am trying to create 2 sort types in my FE with javascript for my items that come from the backend but I don't know what the logic should look like for it. Where can I read about something like this?
The first way would be to sort them by the date (The most recent first)
The second way would be to sort them by the total number of the awards (Highest number first)
This is how my data looks like:
[
{
awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
{
awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
{
awards: {awardOne: 2, awardTwo: 3, awardThree: 2}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
]
Here is an example sorting the data by number of awards in each object: code sandbox. I'm reducing the items in each awards object to a single value and comparing those.
To sort by date, you can use localeCompare like others have pointed out and use a similar pattern.
Update: I just added an working example of sorting by date to the same sandbox
I am thinking you can sort the items by date lexiographically.
Using String.prototype.localeCompare your code would something like
data.sort((a, b) => {
return ('' + a.createdAt).localeCompare(b.createdAt);
}
Source
To sort by number of awards you would need a smaller function, that calculates number of awards, and then write something like:
data.sort((a, b) => {
return (calcNumOfAwards(a) - calcNumOfAwards(b))
}

How to check if array of object contains a string [duplicate]

This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 3 years ago.
let's say I have an array of objects:
let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
I need to check whether that array includes the name 'Jack' for example using:
if (arr.includes('Jack')) {
// don't add name to arr
} else {
// push name into the arr
}
but arr.includes('Jack') returns false, how can I check if an array of objects includes the name?
Since you need to check the object property value in the array, you can try with Array​.prototype​.some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
var r = arr.some(i => i.name.includes('Jack'));
console.log(r);

Javascript: Group similar items in array based on a value [duplicate]

This question already has answers here:
javascript | Object grouping
(16 answers)
Closed 4 years ago.
I have an array of objects like this..
[
{
_id: 123
},
{
_id: 123
},
{
_id: 321
}
]
I want to group similar items by _id and also count how many items of each unique _id there are...
[
{
_id: 123
qty: 2
},
{
_id: 321
qty: 1
}
]
Whats the best way to do this using javascript?
You can do this in O(n) time using Array.prototype.reduce() and a Map as the accumulator:
const array = [{'_id':123},{'_id':123},{'_id':321}]
const groups = [...array.reduce(
(map, { _id }) => map.set(_id, (map.get(_id) || 0) + 1),
new Map()
)].map(
([_id, qty]) => ({ _id, qty })
)
console.log(groups)

How to merge 2 arrays with similar objects? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
IE: I have 2 arrays one with prices, one with names.
The one with prices is longer, and I only want the final array to be the size of the smaller array with only names.
Objects in the prices array:
{
currency: 'BTC',
price: '6500'
},
{
currency: 'NEM',
price: '1'
},
Objects in the name array:
{
currency: 'BTC',
name: 'Bitcoin'
}
The final array should only contain objects that exist in the name array, but also have the price key from the prices array.
{
currency: 'BTC',
name: 'Bitcoin',
price: '6500'
}
I had accomplished this using an NPM package, however the package is old and there is a bug when compiling:
Error while running NPM run build (ERROR in index_bundle.js from UglifyJs)
I also found this answer here: How to merge 2 arrays with objects in one? However none of the answers worked. Neither was the array filtered by the smaller array, but the keys were not combined either.
An alternative is using the function map to generate a new array with the desired output.
This approach uses the function find to retrieve the specific object price related to an object name name.currency === price.currency.
let prices = [{ currency: 'BTC', price: '6500'},{ currency: 'BSS', price: '850'},{ currency: 'USD', price: '905'}],
names = [{ currency: 'BTC', name: 'Bitcoin'},{ currency: 'BSS', name: 'Bolivar'}],
result = names.map(n => Object.assign({}, n, prices.find(p => p.currency === n.currency)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources