The _.uniq() in lodash removes duplicates from an array:
var tst = [
{ "topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w" },
{ "topicId":2,"subTopicId":2,"topicName":"b","subTopicName2":"x" },
{ "topicId":3,"subTopicId":3,"topicName":"c","subTopicName3":"y" },
{ "topicId":1,"subTopicId":4,"topicName":"c","subTopicName4":"z" }]
var t = _.uniq(tst, 'topicName')
This returns:
[ {"topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w" },
{ topicId: 2, subTopicId: 2, topicName: 'b', subTopicName2: 'x' },
{ topicId: 3, subTopicId: 3, topicName: 'c', subTopicName3: 'y' } ]
What's the opposite of this? It should only return a single object for each duplicate object:
[ { topicId: 3, subTopicId: 3, topicName: 'c', subTopicName3: 'y' } ]
I don't think there's a built in method, here's something that should do the job:
function dupesOnly(arr, field) {
var seen = {},
ret = [];
arr.forEach(function(item) {
var key = item[field],
val = seen[key];
if (!val) {
seen[key] = val = {
initial: item,
count: 0
}
}
if (val.count === 1) {
ret.push(val.initial);
}
++val.count;
});
return ret;
}
Related
I'm new to SQL and MongoDB. I'm trying to convert this:
SELECT accountType, ROUND(AVG(balance), 2) avgBalance
FROM customers
WHERE gender="female"
GROUP BY accountType
HAVING COUNT(*) < 140
ORDER BY avgBalance
LIMIT 1
to MongoDB but I can't get it to work. I don't quite understand how the order ($group, $match, $project, $round, $avg etc.) should be and how the "ROUND and AVG" are used together. This is how the answer should be like: { "accountType" : "account-type", "avgBalance" : NumberDecimal("9999.99") }
Here is what I have so far:
db.customers.aggregate( [ { $group: { _id: { accountType: "accountType", avgBalance: { $avg: { "balance" } } }, { $match: { count: { $lt: 140 } } }, { gender: "female" }, { $project: { "accountType": { $round: [ $agv: "balance", 2 ] } } }, { $limit: 1 } ] )
Direction is not bad, would be this one:
db.customers.aggregate([
// WHERE gender="female"
{ $match: { gender: "female" } },
// GROUP BY accountType, SELECT AVG(balance)
{
$group: {
_id: "$accountType",
avgBalance: { $avg: "$balance" },
count: {$sum: 1}
}
},
// HAVING COUNT(*) < 140
{ $match: { count: { $lt: 140 } } },
// SELECT ... AS ...
{
$project: {
accountType: "$_id",
avgBalance: { $round: ["$avgBalance", 2] }
}
},
// ORDER BY avgBalance
{ $sort: { avgBalance: 1 } },
// LIMIT 1
{ $limit: 1 }
])
I have an array of 20 objects which I am getting from a database, each of them has an unique id. I also have an array of data with 2 ids. I want want to filter out only those 2 objects from the array of 20.
computed: {
newHeros(){
return this.getAllHeros.filter(newHero => {
console.log(newHero.id);
return newHero.id === this.heroForTab
})
}
},
return {
heroForTab: ['76NQjrYTdfbWN8xZOAvI', 'uDsm0BValBa31guJs10h']
};
User Array.filter to return what you need
var heroForTab = ['76NQjrYTdfbWN8xZOAvI', 'uDsm0BValBa31guJs10h'];
var arr = [{
id: '76NQjrYTdfbWN8xZOAvI',
name: 'aaa'
},
{
id: '1111',
name: 'bbb'
},
{
id: '2222',
name: 'ccc'
},
{
id: 'uDsm0BValBa31guJs10h',
name: 'ddd'
}
]
var result = arr.filter(item => {
return heroForTab.includes(item.id)
})
console.log(result)
I did a quiz with vue.js and i would like to check if a value is null before put it in the console.log. I Can't find how to do that...
I have a lot of questions to put in this quiz but some of them just need to be ignored in the final result. I just want to bypass all the questions with value:null.
"use strict";
window.onload = function() {
var quiz = {
title: 'Quizz',
questions: [{
text: "Question 1",
responses: [{
text: 'a',
value: null,
},
{
text: 'b',
value: null,
}
]
},
{
text: "Question 2",
responses: [{
text: 'a',
value: '1',
},
{
text: 'b',
value: '2',
}
]
}
]
};
var app = new Vue({
el: '#app',
data: {
quiz: quiz,
questionIndex: 0,
userResponses: Array(),
show: true
},
methods: {
// Go to next question
next: function() {
console.log(this.userResponses);
this.questionIndex++;
},
// Go to previous question
prev: function() {
this.questionIndex--;
},
score: function() {
//find the highest occurence in responses
var userResponses = Array.prototype.concat.apply([], this.userResponses);
var modeMap = {};
var maxEl = userResponses,
maxCount = 1;
for (var i = 0; i < userResponses.length; i++) {
var el = userResponses[i];
if (modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if (modeMap[el] > maxCount) {
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
}
});
}
I find it, just add : var userResponses = this.userResponses.filter(Boolean);
I am using MongoDB version 3.2.8. I am executing db.Member.find({$where: "var d = new Date(this.Birthdate); return d.getUTCDate() === 4 && d.getUTCMonth() === 2 && d.getUTCFullYear() !== 2017" }) It is taking too much time to execute this query on my local mongo. Is there any alternative for this query so query can optimize?
You can try using the MongoDB Aggregation Framework. I tested using the Mingo library for Javascript
Example:
var mingo = require('mingo')
var data = [{
_id: 100,
Birthdate: new Date("1995-02-04")
}]
var pipeline = [
{
$project: { M: { $month: "$Birthdate"}, Y: { $year: "$Birthdate"}, D: { $dayOfMonth: "$Birthdate"}, Birthdate: 1 }
},
{
$match: { $and: [ { D: 4 }, { M: 2 }, {Y: { $ne: 2017 } } ] }
},
{
$project: { M: 0, D: 0, Y: 0 }
}
]
var result = mingo.aggregate(data, pipeline)
console.log(result)
// Output
// [ { Birthdate: 1995-02-04T00:00:00.000Z, _id: 100 } ]
For MongoDB:
db.Member.aggregate(pipeline)
How can I assert that all elements of list are objects?
should.exist(list)
list.should.be.an('array')
... // ?
If we are talking about should, you can use such method:
> var should = require('./');
> var list1 = [1, 2, 3];
> var list2 = [1, { a: 10}, 3];
> var list3 = [{ a: 11}, {b: 10}];
> list1.should.matchEvery(function(it) { return it.should.be.an.Object(); });
AssertionError: expected Array [ 1, 2, 3 ] to match each Function { name: '' }
expected 1 to match Function { name: '' }
expected 1 to be an object
expected 1 to have type object
expected 'number' to be 'object'
at Assertion.fail (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:180:17)
at Assertion.prop.value (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:65:17)
...
> list2.should.matchEvery(function(it) { return it.should.be.an.Object(); });
AssertionError: expected Array [ 1, Object { a: 10 }, 3 ] to match each Function { name: '' }
expected 1 to match Function { name: '' }
expected 1 to be an object
expected 1 to have type object
expected 'number' to be 'object'
at Assertion.fail (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:180:17)
at Assertion.prop.value (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:65:17)
...
> list3.should.matchEvery(function(it) { return it.should.be.an.Object(); });
{ obj: [ { a: 11 }, { b: 10 } ],
anyOne: false,
negate: false,
params:
{ operator: 'to match each Function { name: \'\' }',
message: undefined } }
>
So i have used .matchEvery and checked that each element is object. You can refer to api docs for more examples.