How to Check All Array Element Inside endswith() - javascript

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.

Related

How to compare objects of two arrays in JavaScript

I had taken two arrays in JavaScript
arr1 = ["empid","Name"];
arr2 = [{"keyName":"empid" ,"keyValue":"2"}]
And I want to check the value of keyName should be any one element from arr1.
some short-circuits after finding the first match so it doesn't necessarily have to iterate over the whole array of objects. And it also returns a boolean which satisfies your use-case.
const query1 = ['empid','Name'];
const arr1 = [{'keyName':'empid' ,'keyValue':'2'}];
const query2 = ['empid','Name'];
const arr2 = [{'keyName':'empid2' ,'keyValue':'five'}];
const query3 = ['empid','Name', 'test'];
const arr3 = [{'keyName':'test2' ,'keyValue':'five'},{'keyName':'test' ,'keyValue':'five'}];
function found(arr, query) {
return arr.some(obj => {
return query.includes(obj.keyName);
});
}
console.log(found(arr1, query1));
console.log(found(arr2, query2));
console.log(found(arr3, query3));
Use _.isEqual(object, other);
It may help you.

.includes with array in Javascript

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)

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 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);

Javascript - How to split a string into a nested array?

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);

How to check whether a string contains a substring which is present in a predefined array in JavaScript?

What is the most efficient way to find out if a JavaScript array contains substring of a given string?
For example in case I have a JavaScript array
var a = ["John","Jerry","Ted"];
I need the condition which returns true when I compare the above array against the string:
"John Elton"
For ES6:
var array = ["John","Jerry","Ted"];
var strToMatch = "John Elton"
array.some(el => strToMatch.includes(el))
You can use .some() and .includes() methods:
let arr = ["John","Jerry","Ted"];
let str = "John Elton";
let checker = (arr, str) => arr.some(s => str.includes(s));
console.log(checker(arr, str));
In case you cannot use ES6:
let arr = ["John","Jerry","Ted"];
let str = "John Elton";
var match = arr.some(function (name) {
return str.indexOf(name) > -1;
});
console.log(match);

Categories

Resources