How To Tell If An Array Includes Any Of The Substrings
I have an array with javascript strings that looks something like this: let array = ['cat', 'dog', 'bird'] and I have some words inside my string that are separated by a | this i
Solution 1:
You can check if an animal from the array exists in the string using an Array method .some()
const animals = ['cat', 'dog', 'bird']
const string = 'pig|cat|monkey'
const splitString = string.split('|')
const hasAnimals = animals.some(animal => splitString.includes(animal))
You can get the animals that are present using an Array method .reduce()
const presentAnimals = splitString.reduce((acc, animal) => {
const animalExists = animals.includes(animal)
if (animalExists) {
acc.push(animal)
}
return acc
}, [])
Or if you prefer a one liner
const presentAnimals = splitString.reduce((acc, animal) => animals.includes(animal) ? [...acc, animal] : [...acc], [])
Solution 2:
split
the string by |
and trim
the each word.
Use array includes
to check with some
word.
const has = (arr, str) =>
str.split("|").some((word) => arr.includes(word.trim()));
let array = ["cat", "dog", "bird"];
let string = "pig|cat|monkey";
console.log(has(array, string));
console.log(has(array, "rabbit|pig"));
Solution 3:
Split the string using the character |
, then run a forEach
loop and check if the value of parts
is present in the array.
let array = ['cat', 'dog', 'bird', 'monkey'];
let str = 'pig|cat|monkey';
//split the string at the | character
let parts = str.split("|");
//empty variable to hold matching values
let targets = {};
//run a foreach loop and get the value in each iteration of the parts
parts.forEach(function(value, index) {
//check to see if the array includes the value in each iteration through
if(array.includes(value)) {
targets[index] = value; //<-- save the matching values in a new array
//Do something with value...
}
})
console.log(targets);
I have an array with javascript strings that looks something like this: let array = ['cat', 'dog', 'bird'] and I have some words inside my string that are separated by a | this is the string: let string = 'pig|cat|monkey' so how do I know if my array
includes at least one of these items within my string?
Solution 4:
Try the following:-
let array = ['cat', 'dog', 'bird'];
let string = 'ca';
var el = array.find(a =>a.includes(string));
console.log(el);
Post a Comment for "How To Tell If An Array Includes Any Of The Substrings"