I want to check if an array contains a string and followup on it. indexOf() is not an option because it is strict.
Plunker Here
You can find the described problem in the app.filter('myOtherFilter', function()
app.filter('myOtherFilter', function() {
return function(data, values) {
var vs = [];
angular.forEach(values, function(item){
if(!!item.truth){
vs.push(item.value);
}
});
if(vs.length === 0) return data;
var result = [];
angular.forEach(data, function(item){
if(vs.toString().search(item.name) >= 0) {
result.push(item);
}
});
return result;
}
});
Is this correct and is the error somewhere else?
angular.forEach(data, function(item){
for(var i = 0; i < vs.length; i++){
if(item.name.search(vs[i]) >= 0) {
result.push(item);
}
}
});
You could always extract the Angular filter filter, which takes an array but will handle the different types properly. Here is the general idea:
app.filter('filter', function($filter) {
var filterFilter = $filter('filter');
function find(item, query) {
return filterFilter([item], query).length > 0;
}
return function(data, values) {
var result = [];
angular.forEach(data, function(item) {
for(var i = 0; i < values.length; i++) {
if(find(item, values[i])) {
result.push(item);
break;
}
}
});
return result;
};
}
});
You'll have to change the structure of the data you are passing in. Pass in a list of values, not a list of {truth: true}. This solution allows you to leverage the existing power of the Angular "filter" filter.
Related
Hi guys i am trying to save some information with localStorage in angular, i injected $window to my service and i created a factory call $localStorage
.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);
}
}
}])
i have other factory where i make us of the localStorage factory in order to save some favorites
factory("favoriteFactory", ["$resource", "baseURL", "$localStorage", function($resource, baseURL, $localStorage) {
var favFac = {};
var favorites = $localStorage.getObject("favorites", "[]");
favFac.addToFavorites = function(index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
$localStorage.storeObject("favorites", {id: index});
//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;
}])
the problem is when i add a favorite item, it replaces itself in my array, instead of adding a new one to the array,
i really aprecciate the help
thanks in advance
You are doing wrong while storing. You are replacing an array with a single item. One more thing to note that, Array.prototype.push() return the length of the collection.
enter code herefavFac.addToFavorites = function(index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({id: index})
$localStorage.storeObject("favorites", favorites);
//favorites.push({id: index});
};
You just need to change addToFavorites method like
favFac.addToFavorites = function(index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({id: index});
$localStorage.storeObject("favorites", favorites);
};
Now it will add an item first then save your array into the local storage.
As an advice I suggest you to use ngStorage which enables you to add or remove item from localStorage as simples as a single command:
$localStorage.favorites = [];
That's it and now you have favorites list in localStorage and any time you modify this array you will get results directly on localStorage.
$localStorage.favorites.push(newItemToAdd); // this adds a item.
$localStorage.favorites = $localStorage.favorites
.filter((v, i) => i !== indexOfItemToDelete); // removes item.
I am formatting an array in the function inputCategories, and am unable to correctly add a third argument of "category" - forcing me replicate the function multiple times.
Here is the current state:
Calling the function with arguments.
$scope.categories = inputCategories($scope.item.categories, $scope.settings.categories);
function inputCategories (input, settings) {
var updatedSettings = [];
angular.forEach(input, function(obj) {
updatedSettings.push({"category": obj, "ticked": true});
});
var list = updatedSettings.concat(settings);
list.sort(function(a, b) {
return (a.category > b.category) - (a.category < b.category);
});
for ( var i = 1; i < list.length; i++ ){
if(list[i-1].category == list[i].category) {
list.splice(i,1);
}
}
return list;
};
Here are the places which would require a third argument of "category".
function inputCategories (input, settings) {
var updatedSettings = [];
angular.forEach(input, function(obj) {
updatedSettings.push({****"category"****: obj, "ticked": true});
});
var list = updatedSettings.concat(settings);
list.sort(function(a, b) {
return (a.****category**** > b.****category****) - (a.****category**** < b.****category****);
});
for ( var i = 1; i < list.length; i++ ){
if(list[i-1].****category**** == list[i].****category****) {
list.splice(i,1);
}
}
return list;
};
I think that the issue I am having is because I am mixing up strings and a variable that is a string, inside of the object on the fourth line...?
Perhaps you could do something like this:
function inputCategories (input, settings, category) {
var updatedSettings = [];
angular.forEach(input, function(obj) {
var setting = { "ticked": true };
setting[category] = obj;
updatedSettings.push(setting);
});
var list = updatedSettings.concat(settings);
list.sort(function(a, b) {
return (a[category] > b[category]) - (a[category] < b[category]);
});
for ( var i = 1; i < list.length; i++ ){
if(list[i-1][category] == list[i][category]) {
list.splice(i,1);
}
}
return list;
};
But I want to leave last two duplicated value in array just like
arr = [1,2,3,4,4,4,4,4,5,6,6,6]
and the result will be
result = [1,2,3,4,4,5,6,6]
The reason why I want to leave last two is I have 2 arrays like date and data and it must match with each other.
Thank you.
Using jquery you can use:
var newarr=[];
$.each(arr, function(i, e) {
if ($.inArray(e, newarr) == -1) newarr.push(e);
});
console.log(newarr)
Try this:
var arr = [1,2,3,4,4,4,4,4,5,6,6,6],
result = [],
fisrtOccurence = -1;
for(var i=0; i<arr.length; i++) {
fisrtOccurence = result.indexOf(arr[i]);
if(fisrtOccurence === -1) {
result.push(arr[i]);
} else {
if(result.indexOf(arr[i],fisrtOccurence+1) === -1) {
result.push(arr[i]);
}
}
}
console.log(result);
Try this solution : JSFiddle
var arr = [1,2,3,4,4,4,4,4,5,6,6,6]
// using reduce function of array
Array.prototype.unique = function() {
return this.reduce(function(previousValue, current) {
if (previousValue.indexOf(current) < 0) {
previousValue.push(current);
}
return previousValue;
}, []);
}
console.log(arr.unique());
// using filter
var filteredArray= arr.filter(function(element, index, self) {
return index == self.indexOf(element);
});
console.log(filteredArray);
Demo
Try this
newarr = [];
testarr = [];
duplicatearr = [];
locArray = [1,2,3,4,4,4,4,4,5,6,6,6];
for (var i = 0; i<locArray.length;i++)
{
var idx = $.inArray(locArray[i], testarr);
if (idx == -1) {
testarr.push(locArray[i]);
newarr.push(locArray[i]);
}
else
{
var id = $.inArray(locArray[i], duplicatearr);
if (id == -1) {
newarr.push(locArray[i]);
duplicatearr.push(locArray[i]);
}
}
}
console.log(newarr);
Functions works fine, they filter inventory by barcode, and manufacturer. I want to make it like default angularjs filtering. If I choose manufacturer - LG and barcode - 112 and if they don't match, then it shouldn't display anything.
But for now it displays separately, when i click on filter function it filters barcode when on filter2 function filter manufacturer
$scope.filter = function(barcode) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].barcode == barcode){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
$scope.filter2 = function(manufacturer) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].manufacturer == manufacturer){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
Try this
$scope.filter = function (barcode, manufacturer) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].barcode == barcode || $scope.inventories[i].manufacturer == manufacturer){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
You could create a more general way of filtering:
$scope.filterByBarcode = function(list, key, value) {
return list.filter(function(item){
return item[key] === value;
});
};
And when you filter you could call:
$scope.filtered_inventories = $scope.filter($scope.filter($scope.inventories, 'barcode', 112), 'manufacturer', 'LG')
But to simplify that you could create a function:
$scope.filterByBarcodeAndManufacturer = function(barcode, manufacturer) {
$scope.filtered_inventories =
$scope.filter($scope.filter($scope.inventories, 'barcode', barcode), 'manufacturer', manufacturer);
}
I have json data which contain the whole database record now i need to perform group by on this return json data with sorting on particular category.
I think sorting is easy to do on json data but i am not sure how i can go with group by. I need to group by on particular set of data.
Any help/suggestion would be great help.
Thanks
ravi
var obj = [{ "session":"1","page":"a"},
{ "session":"1","page":"b"},
{ "session":"1","page":"c"},
{ "session":"2","page":"d"},
{ "session":"2","page":"f"},
{ "session":"3","page":"a"}];
function GroupBy(myjson,attr){
var sum ={};
myjson.forEach( function(obj){
if ( typeof sum[obj[attr]] == 'undefined') {
sum[obj[attr]] = 1;
}
else {
sum[obj[attr]]++;
}
});
return sum;
}
var result = GroupBy(obj,"page");
console.log("GroupBy:"+ JSON.stringify(result));
/// GroupBy(obj,"session") --> GroupBy:{"1":3,"2":2,"3":1}
/// GroupBy(obj,"page") --> GroupBy:{"a":2,"b":1,"c":1,"d":1,"f":1}
Check the http://linqjs.codeplex.com or http://jslinq.codeplex.com. It's javascript libraries that mimics LINQ. Here is other questions like yours:Javascript Dynamic Grouping
var obj = [{Poz:'F1',Cap:10},{Poz:'F1',Cap:5},{Poz:'F1',Cap:5},{Poz:'F2',Cap:20},{Poz:'F1',Cap:5},{Poz:'F1',Cap:15},{Poz:'F2',Cap:5},{Poz:'F3',Cap:5},{Poz:'F4',Cap:5},{Poz:'F1',Cap:5}];
Array.prototype.sumUnic = function(name, sumName){
var returnArr = [];
var obj = this;
for(var x = 0; x<obj.length; x++){
if((function(source){
if(returnArr.length == 0){
return true;
}else{
var isThere = [];
for(var y = 0; y<returnArr.length; y++){
if(returnArr[y][name] == source[name]){
returnArr[y][sumName] = parseInt(returnArr[y][sumName]) + parseInt(source[sumName]);
return false;
}else{
isThere.push(source);
}
}
if(isThere.length>0)returnArr.push(source);
return false;
}
})(obj[x])){
returnArr.push(obj[x]);
}
}
return returnArr;
}
obj.sumUnic('Poz','Cap');
// return "[{"Poz":"F1","Cap":45},{"Poz":"F2","Cap":25},{"Poz":"F3","Cap":5},{"Poz":"F4","Cap":5}]"