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

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

Related

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

How to check if a string contains one of the elements from an array in Javascript?

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

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

convert array value to string value with javascript

I have an array
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
i want the result back as string
let strArr = "12,12,43,53,56,7,854,3,64,35,24,67"
Please some one suggest me any solution
You can use toString() method:
let arr = [12,12,43,53,56,7,854,3,64,35,24,67];
arr = arr.toString();
console.log(arr);
console.log(typeof arr);
You can read more about this here.
One solution is to use join method.
The join() method joins the elements of an array into a string, and
returns the string.
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.join();
console.log(strArr);
Use Array.prototype.join().
The join() method joins all elements of an array (or an array-like object) into a string.
var a = [12,12,43,53,56,7,854,3,64,35,24,67];
a.join(); // '12,12,43,53,56,7,854,3,64,35,24,67'
JS type coercion is sometimes useful.
var arr = [12,12,43,53,56,7,854,3,64,35,24,67],
strArr = arr + ""; // <- "12,12,43,53,56,7,854,3,64,35,24,67"
Solution to this would be to use join()
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.join();
Second you be to use toString()
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.toString();
Because you want to join by a comma, they are basically identical, but join allow you to chose a value separator.

Categories

Resources