.includes with array in Javascript - 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)

Related

How to convert comma separated strings enclosed within bracket to array in Javascript?

How to convert below string to array in Javascript? The reason is that I want to take both value separately.
The string is value from an element, when I print it to console I got:('UYHN7687YTF09IIK762220G6','Second')
var data = elm.value;
console.log(data);
You can achieve this with regex, like this for example :
const string = "('UYHN7687YTF09IIK762220G6','Second')";
const regex = /'(.*?)'/ig
// Long way
const array = [];
let match;
while (match = regex.exec(string)){
array.push(match[1]);
};
console.log(array)
// Fast way
console.log([...string.matchAll(regex)].map(i => i[1]))
source
let given_string = "('UYHN7687YTF09IIK762220G6','Second')";
// first remove the both ()
given_string = given_string.substring(1); // remove (
given_string = given_string.substring(0, given_string.length - 1); // remove )
let expected_array = given_string.split(',');
console.log(expected_array);

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

Alphabetically sort array with no duplicates

I'm trying to create a function that takes an array of strings and returns a single string consisting of the individual characters of all the argument strings, in alphabetic order, with no repeats.
var join = ["test"];
var splt = (("sxhdj").split(""))
var sort = splt.sort()
var jn = sort.join("")
join.push(jn)
function removeDuplicates(join) {
let newArr = {};
join.forEach(function(x) { //forEach will call a function once for
if (!newArr[x]) {
newArr[x] = true;
}
});
return Object.keys(newArr);
}
console.log(removeDuplicates(join));
I can not get the current code to work
Check out the comments for the explanation.
Links of interest:
MDN Array.prototype.sort.
MDN Set
var splt = ("sxhdjxxddff").split("")
// You need to use localeCompare to properly
// sort alphabetically in javascript, because
// the sort function actually sorts by UTF-16 codes
// which isn't necessarily always alphabetical
var sort = splt.sort((a, b)=>a.localeCompare(b))
// This is an easy way to remove duplicates
// by converting to set which can't have dupes
// then converting back to array
sort = [...new Set(sort)]
var jn = sort.join("");
console.log(jn);
Something like this :) Hope it helps!
const string = 'aabbccd';
const array = string.split('');
let sanitizedArray = [];
array.forEach(char => {
// Simple conditional to check if the sanitized array already
// contains the character, and pushes the character if the conditional
// returns false
!sanitizedArray.includes(char) && sanitizedArray.push(char)
})
let result = sanitizedArray.join('')
console.log(result);
Try this:
const data = ['ahmed', 'ghoul', 'javscript'];
const result = [...data.join('')]
.filter((ele, i, arr) => arr.lastIndexOf(ele) === i)
.sort()
.join('');
console.log(result)
There are probably better ways to do it, one way is to map it to an object, use the keys of the object for the used letters, and than sorting those keys.
const words = ['foo', 'bar', 'funky'];
const sorted =
Object.keys(
([...words.join('')]) // combine to an array of letters
.reduce((obj, v) => obj[v] = 1 && obj, {}) // loop over and build hash of used letters
).sort() //sort the keys
console.log(sorted.join(''))

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