I have Javascript Filter Item Class and array which is like below
function FilterItem(filterId, filterType) {
this.filterId = filterId;
this.filterType = filterType;
}
var filterItemArray = [];
I am adding Filter Items to this array like below
function AddFilterItem(filterId, filterType) {
filterItemArray.push(new FilterItem(filterId, filterType));
}
I also need to remove item from this array by specific filterId
function RemoveFilterItem(filterId, filterType) {
var item = new filterItem(filterId, filterType);
var itemIndex = jQuery.inArray(item, filterItemArray);
}
But this does not work and I dont think it is the efficient way? My Question is what is the best way to remove this item in RemoveFilterItem Method
Why don't you use the native filter function:
function RemoveFilterItem(filterId, filterType) {
filterItemArray = filterItemArray.filter(function (el) {
return el.filterId !== filterId && el.filterType !== filterType;
});
}
This will give you the array without that element with that id and type.
DEMO
And here's a modified version of Manwal's answer but without the jQuery again:
function RemoveFilterItem(filterId, filterType) {
for (var i = 0, l = filterItemArray.length; i < l; i++) {
var el = filterItemArray[i];
if (el.filterId === filterId && el.filterType === filterType) {
filterItemArray.splice(i, 1);
// because we're caching the length of the array
// we need to adjust the length of l once the splice has taken place
l--;
}
}
}
DEMO
Andy's answer works, but you can make it a lot faster using Array.splice. Manwal's answer uses splice but fails if there are duplicate filters.
I would also use OO code instead of global functions.
function FilterItem(filterId, filterType) {
this.filterId = filterId;
this.filterType = filterType;
}
function FilterItems() {
this.items = [];
}
FilterItems.prototype.add = function (filterId, filterType) {
this.items.push(new FilterItem(filterId, filterType));
}
FilterItems.prototype.remove = function (filterId, filterType) {
for (var i = this.items.length - 1; i >=0 ; i--) {
var item = this.items[i];
if (item.filterId === filterId && item.filterType === filterType) {
this.items.splice(i, 1);
}
}
}
var filters = new FilterItems();
filters.add(1, 1);
filters.add(2, 2);
// Adding two filters of the same type/id to prove that it can remove
// multiple items
filters.add(1, 1);
filters.remove(1, 1);
console.log(filters.items.length);
console.log(filters.items[0]);
You can use $.each to iterate each element of array and then splice it:
function RemoveFilterItem(filterId, filterType) {
var item = new FilterItem(filterId, filterType);
$.each(filterItemArray, function( index, value){
if(value.filterId == item.filterId){
filterItemArray.splice(index,1);
}
});
}
See it in action
No need to create new FilterItem while removing:
function RemoveFilterItem(filterId, filterType) {
$.each(filterItemArray, function( index, value){
if(value.filterId === filterId && value.filterType === filterType){
filterItemArray.splice(index,1);
}
});
}
See Updated Demo
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'm basically trying to loop through an array to check if an item already exists:
If the the item exists, remove it
If the item does not exist, push it to the array
However my code only allows me to add one item only. It ignores every other value I'm trying to add.
var inclfls = []; //new empty array
function addfile(val) {
if (inclfls.length != 0) {
for (var i = 0; i < inclfls.length; i++) {
if (inclfls[i] == val) {
a.style.background = "#999";
inclfls.splice(i, 1); //remove it
}
else {
a.style.background = "#2ECC71";
inclfls.push(val); //push it
}
}
}
else {
a.style.background = "#2ECC71";
inclfls.push(val);
}
alert(inclfls.length);
}
What am I doing wrong?
with array methods, its much simpler:
function addfile(val) {
var index=inclfls.indexOf(val);
if(index===-1){
inclfls.push(val);
a.style.background = "#999";
}else{
inclfls.splice(index,1);
a.style.background = "#2ECC71";
}
}
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);
Cursors can be easily converted to arrays using .toArray(foo) method:
var cursor = col.find({});
cursor.toArray(function (err, itemsArray) {
/* do something */
});
But is it possible to convert itemsArray in a cursor so I will have all cursor functions?
var newCursor = foo (itemsArray);
typeof newCursor.toArray === "function" // true
Well it is all just JavaScript so why not create your own iterator:
var Iterator = function () {
var items = [];
var index = 0;
return {
"createCursor" : function (listing) {
items = listing;
},
"next" : function () {
if ( this.hasNext() ) {
return items[index++];
} else {
return null;
}
},
"hasNext" : function () {
if ( index < items.length ) {
return true;
} else {
return false;
}
}
}
}();
So then you use it like this with an array:
var cursor = new Iterator();
cursor.createCursor( array );
cursor.next(); // returns just the first element of the array
So just a general way to write an iterator. If you want more functionality then just add the other methods to the prototype.
I have some JSON-code which has multiple objects in it:
[
{
"MNGR_NAME": "Mark",
"MGR_ID": "M44",
"EMP_ID": "1849"
},
{
"MNGR_NAME": "Steve",
"PROJ_ID": "88421",
"PROJ_NAME": "ABC",
"PROJ_ALLOC_NO": "49"
}
]
My JSON loop snippet is:
function ServiceSucceeded(result)
{
for(var x=0; x<result.length; x++)
{
}
}
Could you please let me know how to check there is no occurence of "MNGR_NAME" in the array. (It appears twice in my case.)
You need to access the result object on iteration.
for (var key in result)
{
if (result.hasOwnProperty(key))
{
// here you have access to
var MNGR_NAME = result[key].MNGR_NAME;
var MGR_ID = result[key].MGR_ID;
}
}
You could use jQuery's $.each:
var exists = false;
$.each(arr, function(index, obj){
if(typeof(obj.MNGR_NAME) !== 'undefined'){
exists = true;
return false;
}
});
alert('Does a manager exists? ' + exists);
Returning false will break the each, so when one manager is encountered, the iteration will stop.
Note that your object is an array of JavaScript objects.
Could you use something like this?
var array = [{
"MNGR_NAME": "Mark",
"MGR_ID": "M44",
"EMP_ID": "1849"
},
{
"MNGR_NAME": "Steve",
"PROJ_ID": "88421",
"PROJ_NAME": "ABC",
"PROJ_ALLOC_NO": "49"
}];
var numberOfMngrName = 0;
for(var i=0;i<array.length;i++){
if(array[i].MNGR_NAME != null){
numberOfMngrName++;
}
}
console.log(numberOfMngrName);
This will find the number of occurrences of the MNGR_NAME key in your Object Array:
var numMngrName = 0;
$.each(json, function () {
// 'this' is the Object you are iterating over
if (this.MNGR_NAME !== undefined) {
numMngrName++;
}
});
Within the loop result[x] is the object, so if you wanted to count a member that may or may not be present;
function ServiceSucceeded(result)
{
var managers = 0
for(var x=0; x<result.length; x++)
{
if (typeof result[x].MNGR_NAME !== "undefined")
managers++;
}
alert(managers);
}
You can iterate over the collection and check each object if it contains the property:
var count = 0;
var i;
for(i = 0; i < jsonObj.length; i += 1) {
if(jsonObj[i]["MNGR_NAME"]) {
count++;
}
}
Working example: http://jsfiddle.net/j3fbQ/
You could use $.each or $.grep, if you also want to get the elements that contain the attribute.
filtered = $.grep(result, function(value) {
return (value["MNGR_NAME"] !== undefined)
});
count = filtered.length
Use ES6...
myobj1.map(items =>
{
if(items.MNGR_NAME) {
return items.MNGR_NAME;
}else {
//do want you want.
}
})
Thanks.