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";
}
}
Related
I keep array localstorage. I want to delete an element from the array list on another page. My code is below but delete function does not work why?
push.js
existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if (existingEntries == null) existingEntries = [];
entry = {
"adi":path,
};
localStorage.setItem("entry", JSON.stringify(entry));
existingEntries.push(entry);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
delete.js
delete: function (e) {
var del = e.itemData.adi //The information of the clicked element is retrieved.
for (var i = 0; i < dataSource.length; i++) {
if (dataSource[i].adi == del) { dataSource.splice(i, 1); }
}
// insert the new stringified array into LocalStorage
localStorage.getItem("allEntries") =
JSON.stringify(existingEntries);
}
var dataSource = JSON.parse(localStorage.dataSource); //whatever data you want
var del = e.itemData.adi //The information of the clicked element is retrieved.
for (var i = 0; i < dataSource.length; i++) {
if(del === persons[i].name){ //look for match with name
dataSource.splice(i, 1);
break; //exit loop since you found the person
}
localStorage.getItem("allEntries") = JSON.stringify(existingEntries); // insert the new stringified array into LocalStorage
}
exports.equipp = function(user, User, msg) {
var itemname = msg.content.slice(8);
User.find({id: user.id}, function(err, usser) {
for(i = 0; i < usser[0].inventory.length; i++) {
if (usser[0].inventory[i].name == itemname) {
var Item = usser[0].inventory[i];
for (j = 0; j < usser[0].equipped.length; j++) {
if (Item.type == usser[0].equipped[j].type) {
}
if (j == usser[0].equipped.length -1) {
}
}
} else {
if (i == usser[0].inventory.length -1) {
msg.reply("You dont have that Item");
}
}
}
})
}
I'm having some porblems with it at the end at the if (j == usser[0].equipped.length -1) it never goes through and hence never adds an item to a empty inventory. I have items which atm only contain Name, Dmg, and Type im checking if the types match then if they do i add the item to the equipped array and remove it from the items array and vice versa for the item already equipped and when there is no item with that type in the array i need to just add it and remvoe it from the other array but my code fails at the point stated above an array of json objects {
"type": "Healm",
"armor": 4,
"name": "Starter Healm"
},
Instead of this :
for(i = 0; i < usser[0].inventory.length; i++) {
if (usser[0].inventory[i].name == itemname) {
var Item = usser[0].inventory[i];
// rest of code ...
} else {
if (i == usser[0].inventory.length -1) {
msg.reply("You dont have that Item");
}
}
}
Do:
for(i = 0; i < usser[0].inventory.length; i++) {
if (usser[0].inventory[i].name == itemname) {
var Item = usser[0].inventory[i];
// rest of code ...
}
}
if (!Item) {
msg.reply("You dont have that Item");
}
The determining factor whether you found the item is that you have defined Item. It after the loop you find that Item was not set, you know the item was not in the list. This obviously also works when the list is empty.
I have the following code:
function checkIfUnitCostItemsAreZero(finaliseIDList)
{
var selectedItems = finaliseIDList;
selectedItems = $.makeArray(selectedItems); //array is ["-2,-3"]
var getItem = $("#builderItemsList .listItem");
for (i = 0; i < getItem.length; i++)
{
var currentItem = ($(getItem[i]).attr("key"));
if (currentItem.indexOf(selectedItems) > -1)
{//currentItem = "-2" then "-3"
var unitCost = $(getItem[i]).attr("unitcost");
console.log(unitCost);
unitCost = parseFloat(unitCost);
if(unitCost==0.00)
{
return true;
break;
}
}
}
return false;
}
selected item currently equates to the following:
selectedItems = ["-2,-3"]
And further down, currentItem is evaluated at:
"-2", and the next loop "-3".
In both instances, neither go into the if statement. Any ideas why?
Courtesy of Hossein and Aer0, Fixed using the following:
String being passed in as a single value. Use split to seperate it for array.
Modify the if clause.
function checkIfUnitCostItemsAreZero(finaliseIDList)
{
var selectedItems = $.makeArray(finaliseIDList.split(','));
var getItem = $("#builderItemsList .listItem");
for (i = 0; i < getItem.length; i++) {
var currentItem = ($(getItem[i]).attr("key"));
if (selectedItems.indexOf(currentItem) > -1)
{
var unitCost = $(getItem[i]).attr("unitcost");
unitCost = parseFloat(unitCost);
if(unitCost==0.00)
{
return true;
break;
}
}
}
return false;
}
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
I am trying to remove elements of an array which contains either Groups(containing shapes) or simply Shapes(line, Rect, Circle etc) as its elements. My function is something like below:
deleteSelectedShape = function () {
var i,
shapeObj,
selectedObjects = currentContext.getSelectedObjects(),
shapeLayer = currentContext.getShapeLayer();
if (selectedObjects && selectedObjects.length > 0) {
for (i = 0; i < selectedObjects.length; i += 1) {
shapeObj = selectedObjects[i];
// shapeObj.remove(); results same error as mentioned at last
if (shapeObj.nodeType === "Group") {
shapeObj.destroyChildren();
}
else{
shapeObj.destroy();
}
}
}
selectedObjects = [];
shapeLayer.draw();
};
I tried this also
if (shapeObj.nodeType === "Group") {
var childs = [];
childs = shapeObj.getChildren();
for (var j = 0; j < childs.length; j++) {
childs[j].remove();
}
}
else{
shapeObj.remove();
}
}
}
Here Individual shapes are getting deleted but if there is group in array, it is giving error :
TypeError: this.getParent(...) is undefined in Kineticjs file
Please suggest me proper idea. Thank you !!!
One problem: When removing items from an array, you have to iterate through that array in reverse.
var i=selectedObjects.length-1;
while( i-- >=0 ){
var shapeObj = selectedObjects[i];
if (shapeObj.nodeType === "Group") {
shapeObj.destroyChildren();
}else{
shapeObj.destroy();
}
}