2

I have a posList that contains an array of objects. I want to check if the entered value is an exact match of all the posCode in each object of the posList. My RegExp returns true when its a search match. For example, when 4325 is entered it returns true. I only want it to return true if the match is exact.

//short example
posList = [
    {
        posCode: "43252",
        description: "hi"
    },
    {
        posCode: "HTD632",
        description: "hello"
    }
]

checkPosCodeUnique = () => {
    const re = new RegExp(_.escapeRegExp(this.state.posCode), 'i');
    const isMatch = result => (re.test(result.posCode));
    const list = _.filter(this.state.posList, isMatch);
    if (list.length > 0) {
        error=true;
    }

};
xehpuk
  • 7,814
  • 3
  • 30
  • 54
KamSami
  • 387
  • 1
  • 4
  • 14
  • 1
    Possible duplicate of [Matching exact string with JavaScript](https://stackoverflow.com/questions/447250/matching-exact-string-with-javascript) – xehpuk Jan 04 '19 at 20:05
  • 1
    is your list really large (much larger than your example)...if so, you might want to use a dictionary of key value pairs, so you hit on an exact match really fast – Ctznkane525 Jan 04 '19 at 20:25

3 Answers3

2

Why do you need to use regex?

posList = [{
    posCode: "43252",
    description: "hi"
  },
  {
    posCode: "HTD632",
    description: "hello"
  }
]

checkPosCodeUnique = (search) => {
  return posList.some(item => { return item.posCode == search });
};

console.log(checkPosCodeUnique('43252'));
console.log(checkPosCodeUnique('HTD632'));
console.log(checkPosCodeUnique(123));
mbunch
  • 560
  • 7
  • 21
1

Use some method of arrays:

console.log(posList.some(pos => pos.posCode.toUpperCase() === this.state.posCode.toUpperCase());

quirimmo
  • 9,800
  • 3
  • 30
  • 45
1

For what you describe, you don't need regular expressions, you can simply filter the list:

posList.filter(e => e.posCode === posCode)

See https://codesandbox.io/s/5w95r4zmvl for an implementation of your version and the one using a simple filter.

wwerner
  • 4,227
  • 1
  • 21
  • 39