Array.Push() If Does Not Exist

Array.push() if does not exist?

You could extend the Array prototype with a custom method:

// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) {
for(var i=0; i < this.length; i++) {
if(comparer(this[i])) return true;
}
return false;
};

// adds an element to the array if it does not already exist using a comparer
// function
Array.prototype.pushIfNotExist = function(element, comparer) {
if (!this.inArray(comparer)) {
this.push(element);
}
};

var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) {
return e.name === element.name && e.text === element.text;
});

push a object to a array if a specific key is not exists

var bags = [    { product_id: 1 , product_name: "product 1" , quantity: 1 },    { product_id: 2 , product_name: "product 3" , quantity: 1 },    { product_id: 3 , product_name: "product 2" , quantity: 1 }];
function addProduct(product){ var found = false; for( index in bags){ if(bags[index].product_id == product.product_id){ bags[index].quantity += product.quantity; found = true; break; } } if(!found){ bags.push(product); }}
var data = { product_id: 1 , product_name: "product 1" , quantity: 3 };
addProduct(data);console.log(bags);data = { product_id: 10 , product_name: "product 1" , quantity: 3 };addProduct(data);console.log(bags);

prevent pushing objects array if already exist

You can use some to check if the item exists, instead of iterating through the array manually:

   // ...
if (!this.items_local[index].addons.some(e => e.title === addon.title)) {
this.items_local[index].addons.push(addon);
}
// ...

If you really insist on iterating manually, you should be checking if any iteration returned positive, not just the current iteration. In other words:

  // ...
let addonExists = false;
for (let i = 0; i < this.items_local[index].addons.length; i++) {

const element = this.items_local[index].addons[i];
if (element.title === addon.title) {

addonExists = true;
alert('item is exist');
break;
}
}
addonExists || this.items_local[index].addons.push(addon);
// ...

Javascript - Push object in an array only if it does not already exists

Do not push in .forEach(). You need to set a flag (ex. exists), default to false and when you find item in .forEach callback update this flag to true.

When flag is false push to array.

let flag = false;

this.itemsInCart.forEach(el => {
if (el.itemId == itemDetails.objectId) {
el.qty += 1;

flag = true;

return false;
}
})

if (!flag) {
this.itemsInCart.push({
itemId: itemDetails.objectId,
itemName: itemDetails.dishName,
itemPrice: itemDetails.price,
qty: 1
});
}

How to append value to an array only if not exists and remove it if not?

const initialArray = []; // your initial array
const add = []; // stuff you want to add

const { filtered, toAdd } = initialArray.reduce((acc, curr) => {
const index = acc.toAdd.findIndex(v => v === curr);
index === -1 ? acc.filtered.push(curr) : acc.toAdd.splice(index, 1);
return acc;
}, { filtered: [], toAdd: [...add] });

const final = [...filtered, ...toAdd];

And if your initialArray had duplicate values you could just do,

const initialArray = [...new Set(initialArrayWithDuplicates)];

How to push array to object that doesn't exist in object?

The push method is part of the Array prototype in your particular case you are trying to access a not defined property which in JavaScript is consider undefined so you are trying to do transalates into something like:

myObj.third.push => myObj.undefined.push

Because myObj does not have a third key you can try this in the console doing console.log(myObje.third );

So the engine returns an error saying that undefined does not have a property push that is only available in Array.

In this case you need to set assign a value to myObj.third before using it as an array, for that there are multiple ways to set the value as an array your answer above is one of those ways:

myObj['third'] = myObj.third || []

That line works however if for example myObj.third has a value will use that as a value as you are assigning the result of the operation myObj.third || [] which in this scenario anything that evaluates as truthy will be returned if for instance you have:

myObj.third = true; 

And then you do:

myObj.third.push(123);

An error will be displayed Uncaught TypeError: myObj.third.push is not a function as currently myObj.third is not an array.

So you need to make sure you are operating over an Array when using push, or at least when you initialize the value of your property is set as an Array, you can find more details on Array construction on this page.

Alternatives you can do to check before pushing are:

if ( ! Array.isArray(myObj.third) ) {
myObj.third = [];
}

myObj.third.push(123)

if not in array - array.push

$.inArray() returns -1 if the value does not exist in the array. When used as a boolean, -1 equates to true. You need to change your condition to explicitly check for -1:

if ($.inArray(ca, camp) == -1) {
camp.push(ca);
}

Example fiddle

compare two object array and push if not exist

You can use Array.reduce() on base_array, passing array_1 as the initial value and only adding values from base_array where the Date does not already exist in the carry value:

var array_1 = [{  "Date": "2020-04-01",  "Item": 001}, {  "Date": "2020-04-03",  "Item": 002}];var base_array = [{    "Date": "2020-04-01",    "Item": null  }, {    "Date": "2020-04-02",    "Item": null  },  {    "Date": "2020-04-04",    "Item": null  }];
array_1 = base_array.reduce((c, v) => c.concat(c.some(e => e.Date == v.Date) ? [] : [v]), array_1);console.log(array_1);

array.push() method is not adding anything to array and working weirdly

Push changes the original state of the array. So you don't need to re-initialize the array.

 var buttonColors = ["red", "blue", "green", "yellow"];
let temp=[];
temp.push(seq());
console.log(temp);
function seq(){
var randomNumber = Math.floor( Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
return randomChosenColor;
}


Related Topics



Leave a reply



Submit