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?
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], [])
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"));
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?
Try the following:-
let array = ['cat', 'dog', 'bird'];
let string = 'ca';
var el = array.find(a =>a.includes(string));
console.log(el);
Related
let array1 = ["?", "!", "."];
let array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"];
console.log(array2.filter((x) => x.endsWith("?")));
The output is just: ['yep?']
Because the function endsWith() only checked for "?" as you see in the code.
How do I loop the elements on the array1 (suffixes) inside the endsWith function so the output is:
['live.', 'ali!', 'yep?']
You could use a regex, and then match each element in the filter iteration against it.
/[?!.]$/ says match one of these things in the group ([?!.]) before the string ends ($).
const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?'];
const re = /[?!.]$/;
const out = arr.filter(el => el.match(re));
console.log(out);
Regarding your comment you can pass in a joined array to the RegExp constructor using a template string.
const query = ['.', '?', '!'];
const re = new RegExp(`[${query.join('')}]$`);
const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?'];
const out = arr.filter(el => el.match(re));
console.log(out);
You can use an inner .some() call to loop over your array1 and return true from that when you find a match instead of hardcoding the ?:
const array1 = ["?", "!", "."];
const array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"];
const res = array2.filter((x) => array1.some(punc => x.endsWith(punc)));
console.log(res);
Above, when you return true (or a truthy value) from the .some() callback, the .some() method will return true, otherwise it will return false if you never return true, thus discarding it.
i wonder is there any way to check if in a string there are characters that match the characters in array?
const array = ["cake","hello","ok"];
const string = "hello"
let result = string.includes(array)
console.log(result)
// >false
Try to switch array and string:
const array = ["cake","hello","ok"];
const string = "hello"
let result = array.includes(string)
console.log(result)
I think you're looking for Array#some(): loop through the array and check if any of the elements match the predicate.
Here checking if string includes as a substring any of the strings in array.
const array = ["cake","hello","ok"];
const string = "helloaeeahwbdhbd"
let result = array.some(s => string.includes(s))
console.log(result)
I need to compare two arrays for PARTIAL / SUBSTRING matches. If these are found, I want the matching items removed from the originalArray or create a new array with all those items that did not have a partial match,
var originalArray = ['www.google.com/opq', 'www.yelp.com/abc', 'www.yahoo.com/klm', 'www.bing.com/xyz', 'www.google.com/124'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
// DESIRED ARRAY: An array with items that did not have a partial match. For example:
var cleanArray = ['www.yelp.com/abc', 'www.bing.com/xyz']
It work when its a FULL / EXACT match.
But it is NOT what I need.
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['www.google.com/rugby', 'www.yahoo.com/tennis', 'www.google.com/football'];
var cleanObj = {};
itemsToBeRemoved.forEach( e => cleanObj[e] = true);
itemsToBeRemoved.forEach( e => itemsToBeRemoved[e]= true);
var cleanArray = originalArray.filter(function(val){ return !cleanObj [val] })
Logger.log(cleanArray);
}
You can use JavaScript RegExp to create regular expression and array.filter(function) to remove elements that does not match the regex.
Sample Code:
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['google.com', 'yahoo.com', 'google.com'];
// loop through itemsToBeRemove
itemsToBeRemoved.forEach(function(rgx){
// convert each element of itemsToBeRemove to regular expression
var re = new RegExp(rgx);
// filter the array by removing the elements that match the regex
// test() method checks if the string matches the regex
originalArray = originalArray.filter( word => !re.test(word));
});
Logger.log(originalArray);
}
Sample Output:
filter out the elements of the originalArray so that none of the itemsToBeRemoved is present in any of the filtered elements.
There are many ways to check whether a substring is included in another string, as others said, like includes, indexOf and RegExp.
You could then iterate through all of these itemsToBeRemoved in different ways. You could, for example, use some:
function cleanFullMatch(){
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
var cleanArray = originalArray.filter(element => !itemsToBeRemoved.some(item => element.includes(item)));
console.log(cleanArray);
}
Or, alternatively, every:
var cleanArray = originalArray.filter(element => itemsToBeRemoved.every(item => !element.includes(item)));
As you can see, the filtering process can be reduced to a single line.
I have a string var str = "I like roses"; and an array containing var arr1 = ['roses','daisy','lily','petunia']
I want to check if my string contains one or more than one element of the array arr1.
Expected Output : str contains an element from arr1
How can I do that in javascript?
I know how to check all the elements in an array using .every.
var str = 'I will have a mango and a banana';
var arr = ['mango','banana'];
var isEvery = arr.every(item => str.includes(item));
console.log(isEvery);
Output: true
How can I do it for just one element?
Array.prototype.some has already been proposed by #Ele and will likely best suit your needs.
One can take the funky route and use a regex
const v = ['mango', 'banana']
const check = s => !!s.match(new RegExp(`(${v.join('|')})`))
console.log(check('me mango and banana'))//true
console.log(check('me mango'))//true
console.log(check('me nothing'))//false
Not an elegant solution but this should work. Im sure you can clean it up
const arrayCompare = () =>{
const str = "I like roses";
const arr1 = ['roses','daisy','lily','petunia']
const newArray = str.split(' ');
for(let element of newArray){
if(arr1.includes(element)){
return 'String contains element from arr1'
}
}
return false;
};
I know I can use split function to transform a string to an array but how can a string be split twice to produce a nested array?
I expected this would be sufficent but it does not produce the desired output.
var myString = "A,B,C,D|1,2,3,4|w,x,y,z|"
var item = myString.split("|");
var array = [item.split(",")];
Would it be more optimal to use a for each loop?
EXPECTED OUTPUT
var array = [
["A","B","C","D"],
["1","2","3","4"],
["w","x","y","z"],
];
Once you've split on |, use .map to account for the nesting before calling .split again. There's also an empty space after the last |, so to exclude that, filter by Boolean first:
const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
.split('|')
.filter(Boolean)
.map(substr => substr.split(','));
console.log(arr);
Or you could use a regular expression to match anything but a |:
const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
.match(/[^|]+/g)
.map(substr => substr.split(','));
console.log(arr);
var myString = "A,B,C,D|1,2,3,4|w,x,y,z"
var item = myString.split("|");
var outputArr = item.map(elem => elem.split(","));
console.log(outputArr);