Test string with a string list

Viewed 76

I have a list of Id contained in an array :

var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }

I do not see how to do it .. My proposed solution does not work

4 Answers

Don't return false in else, do it outside for-loop once you are sure that items are processed.

for(let i of listId) {
    if(member.userId !== listId[i]) {
      return true;
    }
  }
return false;

Otherwise unless first item's check return true, your method will always return false without checking the rest of the items, since it hasn't got the chance to iterate and process rest of the items.

Yes but I need a variable boolean who return true or false. Like newId because after I do that if(member.userId !== userId && newId) { ... }

Using flag

var flag = false;
for(let i of listId) {
    if(member.userId !== listId[i]) {
      flag = true;
      break;
    }
  }
return flag;

Try this

    if(listId.indexOf(member.userId) !== -1)
     {
      newId = false; 
     }else
      {
       newid = true;
      }

This will work too

return !listId.some(id => member.userId === id);
public listId: string[] = [];

for(let i of this.listId) {
    if(member.userId !== this.listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }

your array not accessing outside foreach loop. you need this operator to access whole value. hope you help.

Related