Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
As an example, how would I determine if "component" is in the array below?
["component.part", "random-component", "prefix-component-name", "component"]
Update:
It seems like my use of false positive was misleading. I meant that it would say that component was in there 4 times, when I want to match the string by itself.
ie. It should return false when checking for the presence of "component" in the below array.
["component.part", "random-component", "prefix-component-name"]
Answer
Use the Array.find
API.
Example:
"use strict";
let items = ["component.part", "random-component", "prefix-component-name", "component"];
let found = items.find(item => { return item === "component.part" } );
if (found) {
console.log("Item exists.");
}
For more usage example.
See:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
No comments:
Post a Comment