9

I have an array of categories: this.categories

[ { "id": 6, "name": "categories.ladies_team" }, { "id": 2, "name": "categories.junior_team" }, { "id": 7, "name": "categories.master" }, { "id": 5, "name": "categories.ladies_single" }, { "id": 1, "name": "categories.junior" }, { "id": 3, "name": "categories.men_single" }, { "id": 4, "name": "categories.men_team" } ]

Now I have a new element:

const newCategory = {
    id: category.id,
    name: category.name
};

I would like to insert it if not present.

I tried:

if (!this.categories.includes(newCategory)) {
    this.categories.push(newCategory);
  }

but it is not working...

What am I doing wrong ?

1
  • 2
    Well, you need to define "not present", and then find if some() element of the array matches the predicate indicating that it's present Commented Jun 13, 2018 at 18:28

3 Answers 3

25

Unfortunately, includes will not work unless it is the same instance. You will need to do something like;

if (!this.categories.some((item) => item.id == newCategory.id)) {
    this.categories.push(newCategory);
}
Sign up to request clarification or add additional context in comments.

1 Comment

some return true/false while find returns the found item in the array or undefined when item is not found. So some is really helpful just to know the existence of the item in array.
5

The solution given by user184994 didn't worked for me, It was only fetching the first element. I tried like this which worked for me.

let data = this.categories.find(ob => ob.id === newCategory.id);
if(data === null){
 this.categories.push(newCategory);
}

1 Comment

if an element is not found then data would be undefined rather then null.
0

Anindyo Bose solution also not working. Replacing null check with undefined works for me.

let data = this.categories.find(ob => ob.id === newCategory.id);
 if(data === undefined){
      this.categories.push(newCategory);
}

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.