how to check a value in array object angularjs - angularjs

i have this array object:
$scope.datas.labels=['10','20','30']
and also i have a function return an array object like this:
response.labels=['10','20','30','50','100','80']
i created a function which recieve the last result..but what i want is to check if a value in response.labels exists in the $scope.datas.labels i dont want to insert it..to avoid duplicated data in $scope.datas.labels, how i can do that??
i tried this but i didnt work:
$scope.concatToData=function (response) {
if($scope.datas.labels=='') {
$scope.datas.labels = $scope.datas.labels.concat(response.labels);
}else {
var i;
for (i = 0; i < $scope.datas.labels.length; i++) {
alert('qa' + JSON.stringify($scope.datas.labels));
alert('res' + JSON.stringify(response.labels));
if ($scope.datas.labels[i] !== response.labels[i]) {
$scope.datas.labels = $scope.datas.labels.concat(response.labels[i]);
} else {
break;
}
}
}
$scope.datas.datasets = $scope.datas.datasets.concat(response.datasets);
}

Try this it will work as per your expectation and requirement.
var arr1=['10','20','30'];
var arr2=['10','20','30','50','100','80'];
for (var i in arr2) {
if(arr2[i] != arr1[i]) {
arr1.push(arr2[i]);
}
}
document.getElementById('result').innerHTML = arr1;
#result {
font-weight:bold;
}
<div id="result"></div>

Take a look at the lodash library, you'll find it useful, and this will be useful for you too:
let common = _.intersection($scope.datas.labels, response.labels);
if (_.size(common) && _.includes(common, 'myValue')) {
// You have a winner;
// This item (myValue) is in both;
} else {
}
Hope that helps.

You can also try that:
var response = ['foo', 'fabio'];
var labels = ['foo'];
var result = response.filter((value) => {
return labels.filter((rs) => {
return rs == value;
}).length == 0;
});
It will return only the data that does not exists on $scope.datas.labels.

Related

Need to use that counter variable outside since if i am calling that function am not getting output return

checkGridData(name: string, searchObj: ElementArrayFinder) {
if (name != "") {
let counter = 0;
let beforesplit = name;
let aftersplit = beforesplit.split("|");
var countval = searchObj.count();
return searchObj.count().then((count) => {
for (let i = 0; i < aftersplit.length; i++) {
let countval = searchObj.count();
// expect(count).toBe(expectedRecords[i]);
for (let j = 0; j < count; j++) {
searchObj.get(j).getText().then(function (text) {
if (text.indexOf(aftersplit[i]) !== -1) {
expect(text).toContain(aftersplit[i]);
++counter
//console.log("counter inside loop is" + counter)
}
return counter;
});
}
}
});
}
}
I am new to protractore. I wrote a function below
I am calling this in another function.
var abc = this.CheckGridData(ProductData.AddEquipment.EquipmentSelection, ProductObj.ele_equipmentvalidation)
console.log("Counter value returned:" + abc)
And i am getting this error
Counter value returned:ManagedPromise::5760 {[[PromiseStatus]]: "pending"}
I tried to do promise but I don't know how to do resolve promise. How to resolve inside for loop in the above, so that i can use it and know the concept? I tried various site but i couldn't understand how to resolve.
Because the function CheckGridData return a promise, so the variable abc is a promise.
To consume the eventual value of promise, you have to use then() as below:
checkGridData(name: string, searchObj: ElementArrayFinder) {
if (name != "") {
let counter = 0;
let beforesplit = name;
let aftersplit = beforesplit.split("|");
return searchObj.getText().then((texts) => {
// texts is an string array of text of all elements of searchObj
for (let i = 0; i < aftersplit.length; i++) {
if(texts.includes(aftersplit[i])) {
++counter;
}
}
return counter;
};
}
}
var abc = this.CheckGridData(ProductData.AddEquipment.EquipmentSelection,
ProductObj.ele_equipmentvalidation)
abc.then(function(count){
console.log(count);
})

AngularJS multiselect custom filter not working as intended

In an AngularJS record display (with filters) I have a multiselect array of territories that a user can select from to find out if a certain item is available in a certain territory.
The array returns a list of values such as
['001','010','200']
based on the ID of the territories selected. This is then checked against a JSON list of records which has a JSON value looks like this
territoriesnotavailable: "001, 085, 090"
Each record either has this set to null, or has a list from one to many numbers.
I currently use the following code (customFilter) which works perfectly if you only select ONE value.. it basically makes the item filter out if the territory selected in the multiselect is in the list of territoriesnotavailable
function CustomTerritoryFilter() {
return function(data, query) {
if (query.length === 0) return data;
if (data) return data.filter(function(item) {
for (var i = 0; i < query.length; i++) {
var queryitem = query[i]["id"];
if(item.territoriesnotavailable) {
stringB = item.territoriesnotavailable;
} else {
stringB = 'xxxxxxxx';
}
stringA = queryitem;
if (!(stringB.indexOf( stringA ) > -1)) {
return data;
}
}
});
return [];
};
}
So if I choose only one filter (resulting in a query of ['010'] for example. and this appears in territoriesnoavailable for the record.. it vanishes as expected.. but if I choose any value that is NOT in territoriesnotavailable the item appears again.. i need the record to vanish if ANY selected territory appears in the list regardless of any that do not
function CustomTerritoryFilter() {
return function(data, query) {
if (query.length === 0) return data;
if (data) return data.filter(function(item) {
for (var i = 0; i < query.length; i++) {
var queryitem = query[i]["id"];
if(item.territoriesnotavailable) {
stringB = item.territoriesnotavailable;
} else {
stringB = 'xxxxxxxx';
}
stringA = queryitem;
if (!(stringB.indexOf( stringA ) > -1)) {
return false;
}
}
return true;
});
return [];
};
}
This is the code that I settled on. It basically sets a flag as 1 (show) and then checks each number in the filter.. if there is just one occurance of the number in the list, the flag is set to zero. At the end of the check data is shown if the flaG REMAins as 1
function CustomTerritoryFilter() {
return function(data, query) {
if (query.length === 0) return data;
if (data) return data.filter(function(item) {
var flag = 1;
for (var i = 0; i < query.length; i++) {
var queryitem = query[i]["id"];
if(item.territoriesnotavailable) {
stringB = item.territoriesnotavailable;
} else {
stringB = 'xxxxxxxx';
}
stringA = queryitem;
if (stringB.indexOf( stringA ) > -1) {
flag = 0;
}
}
if(flag === 1) {
return data;
}
});
return [];
};
}

How to push a JSON object to an array in AngularJS

I need to push a JSON object to AngularJS and need to check before if the value for one of the objects exist. I need to overwrite the data.
$scope.setData = function(survey, choice) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
console.log(keepAllData);
toArray(keepAllData);
alert(JSON.stringify(toArray(keepAllData)));
$scope.keepAllDatas.push({
'surveyId': survey.id,
'choiceId': choice.id
});
var items = ($filter('filter')(keepAllDatas, {
surveyId: survey.id
}));
}
function toArray(obj) {
var result = [];
for (var prop in obj) {
var value = obj[prop];
console.log(prop);
if (typeof value === 'object') {
result.push(toArray(value));
console.log(result);
} else {
result.push(value);
console.log(result);
}
}
return result;
}
If the survey id exists in keepalldata, I need to change the recent value with choiceid. Is it possible to do with AngularJS?
Try with this: Before pushing data you have to check if the survey id exists or not. If it exists you have to update choice with the corresponding survey id, otherwise you can push directly.
$scope.setData = function(survey, choice) {
var item = $filter('filter')(keepAllData, {
surveyId: survey.id
});
if (!item.length) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
} else {
item[0].choiceId = choice.id;
}
console.log(keepAllData);
}
Demo
$scope.keepAllDatas = [];
$scope.setData = function(survey, choice) {
if($scope.keepAllDatas.length == 0) {
$scope.keepAllDatas.push({'surveyId':survey.id,'choiceId':choice.id});
}
else {
var items = ($filter('filter')( $scope.keepAllDatas, {surveyId: survey.id }));
for (var i = items.length - 1; i >= 0; i--) {
// alert(items[i].surveyId);
if(items[i].surveyId == survey.id) {
console.log($scope.keepAllDatas.indexOf(survey.id));
$scope.keepAllDatas.splice($scope.keepAllDatas.indexOf(survey.id),1);
console.log("Removed data")
}
}
$scope.keepAllDatas.push({'surveyId':survey.id, 'choiceId':choice.id});
console.log( $scope.keepAllDatas)
// alert(items[0].surveyId);
}
}

make filter based on data from localstorage in the filter function

I'm new with the Ionic-angular.js, I hope that someone will help me to resolve this problem
First, here is the code
favorites.html
...
<ion-item ng-repeat="dish in dishes | favoriteFilter:favorites" href="#/app/menu/{{dish.id}}" class="item-thumbnail-left" on-swipe-left="deleteFavorite(dish.id)">
<img ng-src="{{baseURL+dish.image}}" on-swipe-left="deleteFavorite(dish.id)">
<h2>{{dish.name}}
<ion-delete-button class="ion-minus-circled"
ng-click="deleteFavorite(dish.id)">
</ion-delete-button>
</ion-item>
...
services.js
.factory('favoriteFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
var favFac = {};
var favorites = [];
favFac.addToFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({id: index});
};
favFac.deleteFromFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
favorites.splice(i, 1);
}
}
}
favFac.getFavorites = function () {
return favorites;
};
return favFac;
}])
.factory('$localStorage', ['$window', function($window) {
return {
store: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
storeObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key,defaultValue) {
return JSON.parse($window.localStorage[key] || defaultValue);
}
//removeItem: function(key){
// $window.localStorage.removeItem(key);
//}
}
controller.js
.filter('favoriteFilter', 'localStorage', function (localStorage) {
if(localStorage.getItem('favorites')!=undefined)
{
var out = [];
return out;
}
else{
return function (dishes) {
var old_favorite = JSON.parse($localStorage.get('favorites'));
var leng = Object.keys(old_favorite).length;
console.log(leng);
var out = [];
for (var i = 0; i < leng; i++) {
for (var j = 0; j < dishes.length; j++) {
if (dishes[j].id === favorites[i].id)
out.push(dishes[j]);
}
}
return out;
}}
});
For the example, there was an array inside the localstorage like this
Key : favorites
value : [{"id":1},{"id":2},{"id":0}]
So, the logic is, I compare the ID between from database and the localstorage based on the ID with the filter function
If the ID is same, so the data from the database gonna push it into the favorites menu.
but, it couldn't show in the favorites menu, and when I checked on the console, it said that
[ng:areq] Argument 'fn' is not a function, got string
Did I make something wrong on here? Or maybe I put a wrong method on here?
Thank you in advance.
The error you present seems to be a syntax problem. You are missing the array brackets.
.filter('favoriteFilter', ['$localStorage', function (localStorage) {
if(localStorage.getItem('favorites')!=undefined)
{
var out = [];
return out;
}
else
{
return function (dishes) {
var old_favorite = JSON.parse($localStorage.get('favorites'));
var leng = Object.keys(old_favorite).length;
console.log(leng);
var out = [];
for (var i = 0; i < leng; i++) {
for (var j = 0; j < dishes.length; j++) {
if (dishes[j].id === favorites[i].id)
out.push(dishes[j]);
}
}
return out;
}
};
}]);
I didn't check your logic function, this will be the answer to solve your error.
Try a different approach:
As you already have addToFavorites and deleteFromFavorites functions, all you have to do is simply follow these 3 steps:
When defining you 'favorites' array, simply assign it as follows:
var favorites = JSON.parse(window.localStorage['favorites'] || []);
In your addToFavorites function, after you push the added item to your array, add: window.localStorage['favorites'] = JSON.stringify(favorites);
In your deleteFromFavorites function, after you splice your array, add: window.localStorage['favorites'] = JSON.stringify(favorites);
You should be good to go with these three super simple steps!

checkbox filter for json array in Angularjs

I have create a filter but this filter is not working with array inside array.
'http://plnkr.co/edit/oygy79j3xyoGJmiPHm4g?p=info'
Above plkr link is working demo.
app.filter('checkboxFilter', function($parse) {
var cache = { //create an cache in the closure
result: [],
checkboxData: {}
};
function prepareGroups(checkboxData) {
var groupedSelections = {};
Object.keys(checkboxData).forEach(function(prop) {
//console.log(prop);
if (!checkboxData[prop]) {
return;
} //no need to create a function
var ar = prop.split('=');
//console.log("ar is - "+ar);
if (ar[1] === 'true') {
ar[1] = true;
} //catch booleans
if (ar[1] === 'false') {
ar[1] = false;
} //catch booleans
/* replacing 0 with true for show all offers */
if(ar[0]=='SplOfferAvailable.text'){
ar[1]='true';
}else{
}
//make sure the selection is there!
groupedSelections[ar[0]] = groupedSelections[ar[0]] || [];
//at the value to the group.
groupedSelections[ar[0]].push(ar[1]);
});
return groupedSelections;
}
function prepareChecks(checkboxData) {
var groupedSelections = prepareGroups(checkboxData);
var checks = [];
//console.log(groupedSelections);
Object.keys(groupedSelections).forEach(function(group) {
//console.log("groupedSelections- "+groupedSelections);
//console.log("group- "+group);
var needToInclude = function(item) {
//console.log("item- "+item);
// use the angular parser to get the data for the comparson out.
var itemValue = $parse(group)(item);
var valueArr = groupedSelections[group];
//console.log("valueArr- "+valueArr);
function checkValue(value) { //helper function
return value == itemValue;
}
//check if one of the values is included.
return valueArr.some(checkValue);
};
checks.push(needToInclude); //store the function for later use
});
return checks;
}
return function(input, checkboxData, purgeCache) {
if (!purgeCache) { //can I return a previous 'run'?
// is the request the same as before, and is there an result already?
if (angular.equals(checkboxData, cache.checkboxData) && cache.result.length) {
return cache.result; //Done!
}
}
cache.checkboxData = angular.copy(checkboxData);
var result = []; // this holds the results
//prepare the checking functions just once.
var checks = prepareChecks(checkboxData);
input.every(function(item) {
if (checks.every(function(check) {
return check(item);
})) {
result.push(item);
}
return result.length < 10000000; //max out at 100 results!
});
cache.result = result; //store in chache
return result;
};
});
above code is for check box filter.
when i click on checkbox called "Availability" it does not filter the result.
Please help me out.
Thanks.
I think that the way you are navigating through json is wrong because if you put in this way it works
"Location": "Riyadh",
"AvlStatus": "AVAILABLE"
"Rooms": {.....
You have to go in some way through Rooms and right now I think you're not doing that

Resources