2

I am using angular and I have an array of Objects let's say Item(SmallItem, Bollean, Boolean) and in my code I add elements to this array by pushing, like for example:

this.Items.push(new Item(smallItem, false, true));

However, I would like to push an Item if and only if item with the same smallItem does not exist in Items. How do I go about it?

1
  • 1
    You can use this.Items.find(x=>x.smallItems==whatever) (return undefined if not find it) Commented Dec 11, 2018 at 8:04

4 Answers 4

5

You can simply go back to the basic and do something along thoses lines :

const itemToAdd = new Item(smallItem, false, true);
if(this.Items.findIndex((item) => item.smallItem === itemToAdd.smallItem) < 0) {
    this.Items.push(itemToAdd);
}

or if you don't want to create the Item if it is not added :

if(this.Items.findIndex((item) => item.smallItem === smallItemToAdd) < 0) {
    this.Items.push(new Item(smallItemToAdd, false, true););
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can remove the items afterward with smallItem in it like

Items.forEach((index,item)=>{
if(item.smallItem){
Items.splice(index,1)
)

Comments

0

an other approach could be:

var find = false;

for (let item of Items) {
// same smallItem value
if(item.smallItem) {
find = true;
}
}

if(!find) {
this.Items.push(new Item(smallItem, false, true));
}

Comments

0

Give this a try:

let items = [
  { name: 'Item 1', booleanA: true, booleanB: true },
  { name: 'Item 2', booleanA: true, booleanB: true },
  { name: 'Item 3', booleanA: true, booleanB: true },
  { name: 'Item 4', booleanA: true, booleanB: true },
  { name: 'Item 5', booleanA: true, booleanB: true }
];

function addItemIfNotAlreadyPresent(itemToAdd) {
  let itemAlreadyExist = items.find(
    item => item.name === itemToAdd.name && item.booleanA === itemToAdd.booleanA && item.booleanB === itemToAdd.booleanB
  );
  if(!itemAlreadyExist) {
    items.push(itemToAdd);
  }
}

let itemAlreadyPresent = { name: 'Item 1', booleanA: true, booleanB: true };
addItemIfNotAlreadyPresent(itemAlreadyPresent);
console.log('Items after trying to add itemAlreadyPresent: ', items);

let itemNotPresent = { name: 'Item 6', booleanA: true, booleanB: true };
addItemIfNotAlreadyPresent(itemNotPresent);
console.log('Items after trying to add itemNotPresent: ', items);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.