If ID exists in javascript array with angularjs - javascript

Okay, I'm done searching and trying code blocks that don't work. This is what I got.
I'm building an array when I click on an image.
invoices.addItem = function(id) {
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : '1'
});
});
}
I want to check to see if the ID passed through when the image is clicked again already exists in the array, if it does increase quantity.
All I'm asking for is a simple way to check if the id exists, if it does return true else return false.
if(id exists)
{
return true;
}
return false;
How do I get the id exists working!?!?!?!?!?!?!?!
UPDATE
This is everything I have:
invoices.addItem = function(id) {
if(invoices.checkItem(id))
{
var index;
for (index = 0; index < invoices.newInvoiceItems.length; ++index) {
if(invoices.newInvoiceItems[index].id === id)
{
var qty = invoices.newInvoiceItems[index].qty;
invoices.newInvoiceItems[index].qty = qty++;
}
else
{
return false;
}
}
}
else
{
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : '1'
});
});
}
}
invoices.removeItem = function(index) {
invoices.newInvoiceItems.splice(index, 1);
}
invoices.checkItem = function(id) {
var index;
for (index = 0; index < invoices.newInvoiceItems.length; ++index) {
if(invoices.newInvoiceItems[index].id === id)
{
return true;
}
else
{
return false;
}
}
}
Let's say I have two items Item A and Item B. If I click on Item A it adds it to the array. Then click it again and it won't add it but only increases qty one time. Now if I click on Item B without refreshing the page mind you, it adds it over and over and over again each time I click on Item B.
I've console logged the id getting returned and it is always the same one, even though each item has it's own ID.

You can use Array.prototype.filter to quickly and easily find an item in an array. If the item is found... then you know it exists.
var existingItem = invoices.newInvoiceItems.filter(function(item){
return item.id === id;
})[0];
if(existingItem ){
++existingItem.qty
}else{
//do your firebase thing...
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : 1
});
});
}

Related

Check for duplicates in database before pushing item logic in JS

Can please someone let me know what's the issue with this code
I run get ref database and store results in obj, then if obj is empty we push new item. Otherwise I run a loop to see if item already exists.
The code not only doesn't follow any logic, but also push 3 items on third try, 4 on 4th and so on.
This is confusing, why it's not working, Checking for strings if equals I have implemented that not sure about the rest
saveIng = (item) => {
const reference = ref(
database,
"users/" + this.state.user + "/ingredients"
);
get(ref(database, "users/" + this.state.user + "/ingredients"))
.then((snapshot) => {
var obj = snapshot.val();
if (obj === null) {
push(reference, {
name: item,
});
} else {
for (let x in obj) {
var found = obj[x].name == item;
if (!found) {
continue;
} else {
push(reference, {
name: item,
});
}
}
}
})
.catch((error) => {
console.log(error);
});
};

AngularJS check condition and return true or false

I have html like this :
<td><span ng-if="isuser(user) == false" type="button" >not allowed</span> </td>
the above html is displayed only if the function isuser(user) return false.
I have an array like this :
$scope.list = ["456", "111", "459"];
Now the user object has an array called id. This id array contains a number key whose value can be 456,111 or 459 and sometimes it may be empty also.
The user object :
{"name":"pravin","status":"Live","id":[{"number":"111"}],"msg":"test"}
Here is the isuser function :
$scope.isuser = function(user) {
for (var i = 0; i < $scope.list.length; i++){
var exists = user.id.find(({number}) => number === $scope.list[i]);
}
if (exists)
return true;
else
return false;
};
but this always returns false.
I want the for loop to check if none of the values of the number key exists in the list array and then only return false.
How do I do it?
The issue is that the below statement
var exists = user.id.find(({number}) => number === $scope.list[i]);
updates every time the exists variable and always you'll get the last change.
One approach could be using some method by passing a callback function as argument.
$scope.isuser = function(user) {
var exists = user.id.some(({number}) => $scope.list.includes(number));
return exists;
}
Try this it will help you
$scope.isuser = function(user) {
var exists = false;
for (var i = 0; i < $scope.list.length; i++){
exists = user.id.find(({number}) => number === $scope.list[i]);
}
if(i==$scope.list.length-1){
if (exists)
return true;
else
return false;
}
loop };

How to add value to array after checking another array

I have two arrays as such :
UserGroupUser[{Id:"1",UserId:"2",UserGroupId"1"},
{Id:"2",UserId:"3",UserGroupId"1"},
{Id:"3",UserId:"4",UserGroupId"2"}]
UserGroupId will have values such as 1, 2, 3 etc.
Employee[{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
I will store a number in a variable GroupId such as GroupId=1
and what i want to do is check the UserGroupUser table if GroupId 1 matches any rows for key UserGroupId and if there is a match for every UserId the corresponding EmployeeId in Employee table that matches would mean i add a new element called enrolled=true. else if there is not match add a element to Employee enrolled=false.
for eg:
If GroupId is =1 then i want to get the userId of those with the UserGroupId as 1 in the UserGroupUser array and add enrolled:true into the Employee array EmployeeId to those corresponding to the UserId .
This is how i tried to do it..
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
result = Employee.map(function (a, index, array) {
while (arrayItem.UserId === a.EmployeeNo) {
a.enrolled = true;
}
return a;
}
);
}
else {
result = Employee.map(function (a, index, array) {
a.enrolled = false;
return a;
}
);
}
});
what am i doing wrong? how should i do this?
Try this
var userGroup = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}]
var employees = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
employees.forEach(function(item){
var found = userGroup.filter(i=>i.UserId==item.Id);
if(found.length>0)
item.enrolled = true
else
item.enrolled = false
})
console.log(employees);
the employees then will contained the enrolled or not try this in your console too
The problem with your code is that when if (arrayItem.UserGroupId === GroupId) { is executed, it changes enrolled to true for the concerned employees but when the else part of this check is executed, it overrides the changes made by the if condition part.
Try this.
UserGroupUser = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}];
Employee = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"}];
GroupId = "1";
Employee.map(function (emp) {
emp.enrolled = false;
});
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
Employee.map(function (emp) {
if (arrayItem.UserId === emp.EmployeeId) {
emp.enrolled = true;
}
});
}
});
console.log(Employee);

AngularJS Function with ng-if inside ng-repeat

I have some times that are calculated dynamically and repeat in an ng-repeat like so:
<div class="col-sm-4" ng-repeat="time in scheduling.openTimes">
<label class="label label-default label-time" ng-class="{'active' : scheduling.militaryTime == time.military}" ng-click="scheduling.setTime(time.military)" ng-if="!scheduling.booked(time.military)">
{{time.display}}
</label>
</div>
And the function scheduling.booked() gets called on each label. It should either return true if the time is "booked" or false if not.
I want the time to display if the time is NOT BOOKED. My function looks like so:
scheduling.booked = function(time)
{
ref.child('appointments').once('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var data = childSnapshot.val();
var sysDate = new Date(scheduling.date);
var appDate = new Date(data.date);
var appTime = data.time.military;
if(appDate.getDay() == sysDate.getDay())
{
if(appTime == time)
{
return true
}
else
{
return false
}
}
else
{
return false
}
})
})
}
It consoles out everything like it should but the label is not hiding? The console shows that is should be.
update
through some research and lots of deleting, I've came up with this. It works and does what I want as long as you only have one appointment. If you have more than one, it duplicates the time slot. How would you make it so it checked if the time was in the array already and skip it if it is?
scheduling.booked = function(time, timeDis) {
ref.child('appointments').once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var data = childSnapshot.val();
var sysDate = new Date(scheduling.date).getDate();
var appDate = new Date(data.date).getDate();
var appTime = data.time.military;
if(sysDate == appDate)
{
if(appTime == time)
{
$scope.openTimes.push({
'military' : time,
'display' : timeDis,
'disabled' : true
})
}
else
{
$scope.openTimes.push({
'military' : time,
'display' : timeDis,
'disabled' : false
})
}
}
else
{
$scope.openTimes.push({
'military' : time,
'display' : timeDis,
'disabled' : false
})
}
})
});
$timeout(function(){
scheduling.openTimes = $scope.openTimes;
scheduling.timeLoading = false;
}, 1300)
}
I have another function calling this one now, I've ditched the ng-if.
Your function scheduling.booked does not have a return. So it will always return undefined. So when angular interprets ng-if="!scheduling.booked(time.military)" will be ng-if="true" (!undefined equals true). This explains why all records are shown.
I think the following code should work.
scheduling.booked = function(time) {
var booked = false;
ref.child('appointments').once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var data = childSnapshot.val();
var sysDate = new Date(scheduling.date);
var appDate = new Date(data.date);
var appTime = data.time.military;
if (appDate.getDay() == sysDate.getDay() && appTime == time) {
booked = true;
}
})
});
return booked; // <-- make sure the function has a return value
}

Excel Type Filter popup for Jqgrid

I need to have a filter ( like in Excel spread Sheet) to embedded to the 'jquery' dialog popup. in this case i need to show all the unique values in the column and check box just before that value to select to the user. when user pressed filter button i need to filter only the values that user requested through the check boxes.
Can any one please let me any approach that i must follow.
Thanks in advance for your help and valuable time.
I was able to develop basic grid with excel kind of filter feature. any one who will come across this type of requirement can use this answer as a foundation.
I use this answer from 'Oleg' to embed the filter popup screen to the basic 'jqgrid'.
in the jqgrid page declare this array with the attributes (columns) that needs to display the filter screen popup.
var applyFilterColumnNames = ['Id','Type','custId','UserId'];
and the column model should be as follows -
colModel :[
{name:'Id', index:'Id',hidden: true,sortable: true},
{name:'custId', index:'custId', width:140,align:"left",sortable: true,search : false},
{name:'Type', index:'Type', width:120,align:"left",sortable: true,search : false},
{name:'UserId', index:'UserId', width:150,align:"left",sortable: true,search : false},
],
used that reference answer to embed the filter button function.
gr.closest("div.ui-jqgrid-view").find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-jqgrid-labels > th.ui-th-column > div.ui-jqgrid-sortable")
.each(function () {
var idPrefix = "jqgh_" + gr[0].id + "_";
var idIndex = (this.id).substr(idPrefix.length,this.id.length) ;
if(includeInArray(applyFilterColumnNames,idIndex)){
jq('<button id=btn_'+idIndex+'>').css({float: "right", height: "17px"}).appendTo(this).button({
icons: {
primary: "ui-icon-gear"
},
text: false
}).click(function (e) {
var idPrefix = "jqgh_" + gr[0].id + "_";
// thId will be like "jqgh_list_name"
var thId = jq(e.target).closest('div.ui-jqgrid-sortable')[0].id ;
if (thId.substr(0, idPrefix.length) === idPrefix) {
var colName = thId.substr(idPrefix.length);
//alert('Clicked the button in the column "' + colName + '"');
constructFilter(colName);
return false;
}
});
//}
}
});
Below is the script i used to filter the jqgrid according to the filters
//Variables that use in filtering operation
var originalData = null;
var filteredData;
var selectedFilters = new Object();
var chkBoxElement;
var firstSortColumn;
function constructFilter(columnName){
// for the first initiation of the filter populate current grid data to an array
if(originalData == null || originalData == 'null'){
try{
// this array will hold the initail data set of the grid
originalData = gr.jqGrid('getGridParam','data');
// set the first sorting grid column
firstSortColumn = columnName;
// check if column is associated with a formatter. if so format the originalData values accordingly.
formatGridData(columnName);
}catch(e){}
}
var colData = new Array();
var filterDataSet;
// if current column is equal to initial sorted column set all posible values to the check boxes in the
// filter screen to select. ( since this is the master sorting column and other columns will filter according to that)
if(columnName == firstSortColumn){
filterDataSet = originalData;
}else{
// set current grid data set to show as checkboxes in the filter page
filterDataSet = gr.jqGrid('getCol',columnName,false);
}
for(key in filterDataSet){
// check box element object that will hold the checkbox label and its state ( true / false)
chkBoxElement = new Object();
chkBoxElement.id = getValueFromArray(filterDataSet[key],columnName);
if(typeof(chkBoxElement.id)== 'undefined'){
break;
}
// if this id is saved in previous filtering event checked option will set to true.
if(typeof(selectedFilters[columnName]) != 'undefined'){
if (includeInArray(selectedFilters[columnName],chkBoxElement.id)){
chkBoxElement.selected = true;
}else{
chkBoxElement.selected = false;
}
}
colData.push(chkBoxElement);
}
// removing duplicates
var uniqueValues = removeDuplicates(colData);
// sort the array without duplicate with the custom comparator
uniqueValues.sort(sortComparator);
// open the filter screen. return type will captured in the 'seletedElements' variable as pipe separated string
seletedElements = window.showModalDialog(filterUrl,uniqueValues,"dialogWidth:400px;dialogHeight:250px;center:yes;resizable:no;status:no;help:no;");
if(seletedElements != null && seletedElements != 'null'){
// get selected values to the array
selectedFilters[columnName] = seletedElements.split("|");
}else{
//user just close the popup (using close button) will return without doing anything
return;
}
if(columnName == firstSortColumn){
// refine filter with the non filtered data set
refillGrid(seletedElements,columnName,originalData);
}else{
// send current data set to refine
var currentDataSet = gr.jqGrid('getGridParam','data');
refillGrid(seletedElements,columnName,currentDataSet);
}
}
function formatGridData(columnName){
var isFormatter = gr.jqGrid("getColProp",columnName);
if(typeof isFormatter.formatter !== 'undefined') {
if(jq.isFunction( isFormatter.formatter ) ) {
for(key in originalData){
var plainValue = originalData[key][columnName];
var formattedVal = isFormatter.formatter.call(null,plainValue,null,null,null);
originalData[key][columnName] = formattedVal;
}
}
}
}
function resetFilters(){
for(key in applyFilterColumnNames){
jq("#btn_"+applyFilterColumnNames[key]).button("option", {
//icons: { primary: this.checked ? 'ui-icon-check' : 'ui-icon-closethick' }
icons: { primary: 'ui-icon-gear'}
});
}
gr.jqGrid("setCaption",gridCaption);
refreshGrid(originalData);
originalData = null;
firstSortColumn = null;
selectedFilters = new Object();
}
function refillGrid(seletedElements,columnName,filterDataSet){
var filteredData= new Array();
var elementsArray;
try{
elementsArray = seletedElements.split("|");
}catch(e){
// this exception happens when user simply open the filter screen
// do nothing and close it.
trace('Error in filter splitting -'+e);
return;
}
// When user de-select all check boxes from the popup screen
if(elementsArray == ""){
refreshGrid(originalData);
return;
}
// refine the grid data according to the filters
var mydata = filterDataSet;
for(i=0;i<elementsArray.length;i++){
var filterElement = elementsArray[i];
for(j = 0;j<mydata.length;j++){
if(filterElement==getValueFromArray(mydata[j],columnName)){
filteredData.push(mydata[j]);
}
}
}
// change the button icon to indicate that the column is filtered
changeButtonIcon(columnName);
// update the column header to indicate sort by column
changeGridCaption(columnName);
// fill the grid according to the passed array
refreshGrid(filteredData);
}
function changeGridCaption(columnName){
// get columns name array
var columnNames = gr.jqGrid('getGridParam','colNames');
// get column model array
var colModel = gr.jqGrid('getGridParam','colModel');
var colModelIndex=null;
if (firstSortColumn == columnName){
for(key in colModel){
try{
if (colModel[key].name == firstSortColumn){
colModelIndex = key;
break;
}
}catch(e){}
}
if(colModelIndex != null){
var columnName = columnNames[colModelIndex];
gr.jqGrid("setCaption",gridCaption + " - Filtered based on : "+columnName);
}
}
}
function changeButtonIcon(columnName){
//change the button Icon
jq("#btn_"+columnName).button("option", {
//icons: { primary: this.checked ? 'ui-icon-check' : 'ui-icon-closethick' }
icons: { primary: 'ui-icon-link'}
});
}
function getValueFromArray(obj,columnName){
if(obj !=null && typeof(obj)!='undefined'){
// if obj param is string just return it
if(typeof obj =='string'){
return obj;
}else{
return obj[columnName];
}
}
}
function sortComparator(a,b){
try{
var aId = a.id.toLowerCase();
var bId = b.id.toLowerCase();
if (aId < bId) {return 1}
if (aId > bId) {return -1}
}catch(e){
return 0;
}
}
function includeInArray(arr,obj) {
//alert(arr);
return (arr.indexOf(obj) != -1);
}
function refreshGrid(results) {
gr.jqGrid('clearGridData')
.jqGrid('setGridParam', { data: results })
.trigger('reloadGrid');
}
function removeDuplicates(valueArray){
var arr = {};
for ( i=0; i < valueArray.length; i++ ){
if(valueArray[i].id != null){
arr[valueArray[i].id] = valueArray[i];
}
}
valueArray = new Array();
for ( key in arr ){
valueArray.push(arr[key]);
}
return valueArray;
}
If something wrong here please let me know.this solution is working fine. but i really appreciate the comments in therms of performance and code best practices.

Categories

Resources