2

How do check if ticketId already inserted into array?

This is the code:

state = { myState: [], status: 0, limit: 5 };

  selected(ticketId) {
  if (this.state.status < this.state.limit) { 
    this.state.myState.push({ id: ticketId }); //what ever i chose get inserted
    this.state.status++;
    this.setState({ status: this.state.status }); 
    //console.log('here', this.state.status);
  } else {
    console.log('3'); //check if condition meet
  }
 }

How do I create a condition checking myState array if the ticketId already insert and trigger an alert?

2 Answers 2

3

As you are storing as an object {id:value}, better use "every" instead.

state = { myState: [], status: 0, limit: 5 };

selected(ticketId) {
   if (this.state.status < this.state.limit ) { 
      if(this.state.myState.every((item) => item.id !== ticketId)){
        this.state.myState.push({ id: ticketId }); //what ever i chose get inserted
        this.state.status++;
        this.setState({ status: this.state.status }); 
      //console.log('here', this.state.status);
     }
   } else {
   console.log('3'); //check if condition meet
   } 
}
Sign up to request clarification or add additional context in comments.

Comments

3

Hello you can use loadash Find it Here for this kind of problems its easy and very good looking! :)

Example:1

_.indexOf([1, 2, 1, 2], 2);
// => 1

Or You can Use

Example:2

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0

// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1

// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0

// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2

In your code

_.findIndex(this.state.myState, { 'id': ticketId });
// It will return 0 if there is nothing 
// else will return no of index 
// where it ticketid is present 
// you can do alert on if its not 0

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.