Match all possible combinations of substring in array - javascript

Assuming I have an input string like "auto encoder" and array of strings
const arr = ['autoencoder', 'auto-encoder', 'autoencoder']
I want the input string to match with all three in array.
I created regex
arr.some(word => word.match(/^[a-zA-Z]+(?:(?:\s[a-zA-Z]+)+|(?:\-[a-zA-Z]+)|(?:[a-zA-Z]+))$/))
but seems it doesn't work as if I test it against an array with a single element like ['auto-encoder'] it returns nothing.
How can I achieve desired matching?

function isIncluded(str, arr) {
str = str.replace(/\W/g, '');
return arr.some(e => (e.replace(/\W/g, '') === str));
}

What about replacing special characters (non-word characters) and comparing with the array?
const arr = ['auto encoder', 'autoencoder'];
const fn = (s, a) => a.includes(s.replace(/\W/g, ''));
console.log(fn('auto-encoder', arr));
console.log(fn('a u t o e n c o d e r', arr));
console.log(fn('random', arr));

I think your input is gonna be a string, not an array of strings. You have already the regex, you just need to define a function around it:
function f(word) {
return word.match(/^[a-zA-Z]+(?:(?:\s[a-zA-Z]+)+|(?:\-[a-zA-Z]+)|(?:[a-zA-Z]+))$/);
}
And if you rinput is gonna be an array you can use various array methods:
If you want a boolean answer if some elements match
function f(arr) {
return arr.some(word => word.match(/^[a-zA-Z]+(?:(?:\s[a-zA-Z]+)+|(?:\-[a-zA-Z]+)|(?:[a-zA-Z]+))$/));
}
If you want to know if all elements match use every instead of some
You have other options. For having the array of the matches use filter:
function f(arr) {
return arr.filter(word => word.match(/^[a-zA-Z]+(?:(?:\s[a-zA-Z]+)+|(?:\-[a-zA-Z]+)|(?:[a-zA-Z]+))$/));
}
You could answer your function(s) according to what you want to achieve with each one.

Related

Javascript: includes return false while matching partial array element

Very simple example here:
var u = []
u.push("https://cloudinary.com/products/media_optimizer/web-performance-guide#get-started")
u.includes("https://cloudinary.com/products/media_optimizer/web-performance-guide") //return false
What am I doing wrong here?
Iterate over the array, checking each element.
const search = (arr, fragment) => arr.some(v => v.includes(fragment));
const u = [
"https://cloudinary.com/products/media_optimizer/web-performance-guide#get-started"
];
const found = search(u, "https://cloudinary.com/products/media_optimizer/web-performance-guide");
console.log(found);
Reference:
.some()
The value you are searching for must be an exact match, and you are not searching for the ending #get-started
You are searching the array for an exact match to your string.
You can use .includes(...) on the string in the array which will return true.
u[0].includes("https://cloudinary.com/products/media_optimizer/web-performance-guide")
your error is to use the includes in an array, the method is for a string value
string.includes(searchvalue, start)
for this to work you need to iterate the array:
u.map(item => item.includes("https://cloudinary.com/products/media_optimizer/web-performance-guide"))

How to split pipe separated string into array of object

I have pipe separated string (sshshhs , 1) | (ee23es , 1) , I want to split and make an array of object . Result must be like [ {name:sshshhs,value:1},{name:ee23es,value:2} ]. I am new to JavaScript could someone please help me .
Thanks
Check out this code snippet
let myString = "(sshshhs , 1) | (ee23es , 1)";
// extract only the elements
let stringList = myString .split(/\) \| \(|\(|\)/);
// remove first and last empty elements, due to regex
stringList = stringList.slice(1,-1);
//split each element into an object
let objList = stringList.map(s => {
const [name, value] = s.split(',').map(el => el.trim());
return { name, value };
})
In this way with one regex you get rid of pipe and parenthesis. Then with a map you extract the name and value from each element.
You have multiple ways to transform your string into an array of object
One of them could be to split multiple times and use reduce to make the object
"(sshshhs , 1) | (ee23es , 1)"
.split('|') // here we first split with the principal key
.map(e => {
return [e.replace(/\(|\)/g, '')] // we create an object of your values to reduce it
.reduce((result, token) => {
const [name, value] = token.split(',').map(e => e.trim()); // we get the key/values by splitting it (and trimming it by the same time)
return {name, value}; // we then return the finded name and value
}, {})
})
This is definitly not the most efficient way to do it, but it will help you understand the mechanics behind split and reduce and help you create your own solution

How to convert string in an array?

From http response I received an object like this:
{"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
The key is an array...Is there a way in typescript to convert the key
"[3, company1]"
in an array like this
[3, "company1"]
?
You can combine Object.keys with map and transform the string to array with split
let data = {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
let keys = Object.keys(data)
.map(
el =>
el.replace('[', '')
.replace(']', '')
.split(',')
.map(el => el.trim())
.map(el => isNaN(parseFloat(el))
? el
: parseFloat(el))
)
console.log("Keys: ", keys)
Here is the fiddle:
https://jsfiddle.net/to38g6cb/1/
What do you want to convert the keys to?
if want to convert it to a normal array then the below should do.
const httpResponse = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
};
const convertedKeys = Object.keys(httpResponse).map(value => {
let keyArray = value.replace("[", "").replace("]", "").split(", ");
return [parseInt(keyArray[0]), keyArray[1]];
});
console.log(convertedKeys);
If the above is not what you wanted, please kindly rephrase your question again.
You can remove the first and last character using slice(1,-1) and split the string at /\s*,\s*/ (comma with optional spaces on either side).
Then convert the first part to a number and return the array
const input = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
}
const output = Object.keys(input).map(k => {
const [n, comp] = k.slice(1,-1).split(/\s*,\s*/)
return [+n, comp]
})
console.log(JSON.stringify(output))
It would have been easier if the company1 part were already quoted, so that you could just use JSON.parse. In fact, let's just do that! Put quotes around the company1 part with search and replace.
let key = `[3, company1]`;
let obj = JSON.parse(key.replace(/[$A-Z_]\w*/gi, '"$&"'))
console.log(obj);
Note: I'm guessing at what characters might be valid and went with something that looks vaguely like a JavaScript identifier. [$A-Z_]\w* Obviously not commas and right square brackets, due to deserialization ambiguity.

JS Array.splice return original Array and chain to it

I have a string with values like this a,b,c,d and want to remove a specific letter by index
So here is what I did str.split(',').splice(1,1).toString() and this is (obviously) not working since splice is returning the values removed not the original array
Is there any way to do the above in a one liner?
var str = "a,b,c,d";
console.log(str.split(',').splice(1,1).toString());
Thanks in advance.
You can use filter and add condition as index != 1.
var str = "a,b,c,d";
console.log(str.split(',').filter((x, i) => i != 1).toString());
Another strange solution. Destructure the array, remove the unwanted index, get an object and join the values of it.
var string = "a,b,c,d",
{ 1: _, ...temp } = string.split(',')
console.log(Object.values(temp).join(','));
The alternate way using regex replace
var str = "a,b,c,d";
console.log(str.replace(/,\w+/, ''))
Splice works in place, so oneliner is
const arr = "a,b,c,d".split(','); arr.splice(1,1); console.log(arr.toString());
If you want an string in a oneliner, you have to hardcode the index in a filter
console.log("a,b,c,d".split(',').filter((item, i) => i != 1).toString())
Or two slices (not performant at all)
const arr = "a,b,c,d".split(',')
console.log([...arr.slice(0,1),...arr.slice(2)].toString())

Find the index of a string that contains a substring in an array

I'm trying to find the index of a string element that contains a substring in an array. I tried Array#indexOf, but it always returns -1.
What am I doing wrong?
var array = ["OTHER-REQUEST-DEPT1", "OTHER-REQUEST-DEPT2", "OTHER-REQUEST-DEPT3"]
var string = "DEPT2"
console.log(array.indexOf(string));
Array.indexOf() finds the index of the array item that equals its parameter.
You don't have any array elements that equal "DEPT2".
It sounds like you want to check whether the array contains (or find the index of) any element that contains your string, using .some() or .findIndex() with an arrow function that calls item.includes(string).
Expanding on the answer by SLaks, here are a few functioning examples achieving different outcomes based on the location of a string that contains a substring in an array.
const array = ["OTHER-REQUEST-DEPT1","OTHER-REQUEST-DEPT2","OTHER-REQUEST-DEPT3"];
const string = "DEPT2";
console.log(array.find (e => e.includes(string)));
console.log(array.findIndex(e => e.includes(string)));
console.log(array.some (e => e.includes(string)));
console.log(array.reduce ((m, e, i) => e.includes(string) ? Object.assign(m, { [i]: e }) : m, {}));
console.log(array.filter (e => e.includes(string)));

Categories

Resources